LazyProperty¶
- class pyinaturalist.models.LazyProperty(converter, name=None, doc=None, type=<class 'pyinaturalist.models.base.BaseModel'>, **converter_kwargs)¶
Bases:
propertyA lazy-initialized/cached descriptor for
attrsclasses. Its purpose is similar to@functools.cached_property, but it works for slotted classes by not relying on__dict__.Currently this is used to lazy-load nested model objects for better performance.
How it’s used:
Define an
attrsclassUse
add_lazy_attrsas a field_transformer for the class, which adds a temporary attributesDefine a
LazyPropertyclass attribute with a converter
How it works:
During attrs init, the temporary attribute is set containing a raw dict
When
foois first accessed, it runs the converter on the temp attributeWhen
foois accessed again, the previously converted temp attribute will be returned
Example:
# Just pretend these are expensive conversion functions def converter_func(value) -> str: return str(value) def list_converter_func(value) -> List: return [value] @attrs.define(field_transformer=add_lazy_attrs) class MyModel(BaseModel): str_field = LazyProperty(converter_func) list_field = LazyProperty(list_converter_func) # Auto-generated temp attributes will look like: # _str_field = field(default=None) # _list_field = field(factory=list)
Methods
- __init__(converter, name=None, doc=None, type=<class 'pyinaturalist.models.base.BaseModel'>, **converter_kwargs)¶
- deleter()¶
Descriptor to obtain a copy of the property with a different deleter.
- get_lazy_attr() Attribute¶
Get a temp attribute to be used by this LazyProperty instance
- Return type:
Attribute
- getter()¶
Descriptor to obtain a copy of the property with a different getter.
- setter()¶
Descriptor to obtain a copy of the property with a different setter.