Skip to content

cached_property vs property #11

@hanslovp-gne

Description

@hanslovp-gne

@property is used a few times, with a cache that is initialized as None, e.g. here:

    @property
    def dim_names(self) -> List[str]:
        """Get dimension names of the array."""
        if self._dim_names is None:
            with self.open_array(mode="r") as A:
                self._dim_names = [dim.name for dim in A.schema.domain]
        return self._dim_names

This could be simplified with @functools.cached_property. This is not entirely the same as using property with a cache that is initialized to None, but might be identical for our use case. This is also available in Python 3.8+, so it should be Ok for the supported versions (3.9+). The benefit would be that we don't have to initialize the cache as None anymore, and also not have the None check in the getters either. We could entirely focus on the business logic.

Note: I am not suggesting that we need to move to @cached_property. In fact, most of my code still uses @property the same way as here, because I only recently became aware of @cached_property. I just want to raise awareness that this exists and that we could use it if we think it helps with the readability. There is also a downside to @cached_property for python < 3.12: It locks for thread safety, which is not useful for any of the use cases that I am aware of.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions