LazyProperty¶
- class pyinaturalist.models.LazyProperty(converter, name=None, doc=None, type=<class 'pyinaturalist.models.base.BaseModel'>)¶
Bases:
property
A lazy-initialized/cached descriptor, similar to
@functools.cached_property
, but works for slotted classes by not relying on__dict__
.Currently this is used to lazy-load nested model objects for better performance. How it works:
Define a LazyProperty on a model, say
MyModel.foo
Use add_lazy_attrs as a field_transformer for the model, which adds an attr.field
_foo
During attrs init,
_foo
is set from response JSONWhen
foo
is first called, it converts_foo
from JSON into a model objectWhen
foo
is called again the previously converted_foo
object will be returned
Example:
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 fields will look like: # _str_field = field(factory=list) # _list_field = field(default=None)
Attributes
Methods
- __init__(converter, name=None, doc=None, type=<class 'pyinaturalist.models.base.BaseModel'>)¶
- deleter()¶
Descriptor to change the deleter on a property.
- get_lazy_attr()¶
Get an attribute corresponding to this LazyProperty instance
- Return type
Attribute
- getter()¶
Descriptor to change the getter on a property.
- setter()¶
Descriptor to change the setter on a property.