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:

  1. Define an attrs class

  2. Use add_lazy_attrs as a field_transformer for the class, which adds a temporary attributes

  3. Define a LazyProperty class attribute with a converter

How it works:

  1. During attrs init, the temporary attribute is set containing a raw dict

  2. When foo is first accessed, it runs the converter on the temp attribute

  3. When 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)

Attributes

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.