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:

  1. Define a LazyProperty on a model, say MyModel.foo

  2. Use add_lazy_attrs as a field_transformer for the model, which adds an attr.field _foo

  3. During attrs init, _foo is set from response JSON

  4. When foo is first called, it converts _foo from JSON into a model object

  5. When 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.