Skip to content

[typing] distribution.lazy_property is not typed #76772

@ssnl

Description

@ssnl

🐛 Describe the bug

lazy_property is not typed, but widely used in distribution attributes, e.g., bernoulli_distn.probs:

class lazy_property:

This makes writing typed code w/ distributions ugly (e.g., having to use cast(..)).

Please consider making it typed, e.g.,

T = TypeVar('T')


class lazy_property(Generic[T]):
    r"""
    Used as a decorator for lazy loading of class attributes. This uses a
    non-data descriptor that calls the wrapped method to compute the property on
    first call; thereafter replacing the wrapped method into an instance
    attribute.
    Derived from:
      https://github.com/pytorch/pytorch/blob/556c8a300b5b062f3429dfac46f6def372bd22fc/torch/distributions/utils.py#L92
    """

    def __init__(self, wrapped: Callable[[Any], T]):
        self.wrapped = wrapped
        functools.update_wrapper(self, wrapped)

    def __get__(self, instance: Any, obj_type: Any = None) -> T:
        if instance is None:
            return self  # typing: ignore
        value = self.wrapped(instance)
        setattr(instance, self.wrapped.__name__, value)
        return value

Versions

all versions

cc @fritzo @neerajprad @alicanb @nikitaved

Metadata

Metadata

Assignees

No one assigned

    Labels

    module: distributionsRelated to torch.distributionstriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions