LazyProperty¶
- class pyinaturalist.models.LazyProperty(converter, name=None, doc=None, type=<class 'pyinaturalist.models.base.BaseModel'>, **converter_kwargs)¶
Bases:
property
A lazy-initialized/cached descriptor for
attrs
classes. 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
attrs
classUse
add_lazy_attrs
as a field_transformer for the class, which adds a temporary attributesDefine a
LazyProperty
class attribute with a converter
How it works:
During attrs init, the temporary attribute is set containing a raw dict
When
foo
is first accessed, it runs the converter on the temp attributeWhen
foo
is 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()¶
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.