8000 added type hints to `lazy_property` by randolf-scholz · Pull Request #144106 · pytorch/pytorch · GitHub
[go: up one dir, main page]

Skip to content

added type hints to lazy_property #144106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
8000
Diff view
29 changes: 22 additions & 7 deletions torch/distributions/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# mypy: allow-untyped-defs
from functools import update_wrapper
from numbers import Number
from typing import Any, Dict
from typing import Any, Callable, Dict, Generic, overload, TypeVar

import torch
import torch.nn.functional as F
Expand Down Expand Up @@ -130,19 +130,34 @@ def probs_to_logits(probs, is_binary=False):
return torch.log(ps_clamped)


class lazy_property:
T = TypeVar("T", covariant=True)


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.
"""

def __init__(self, wrapped):
self.wrapped = wrapped
def __init__(self, wrapped: Callable[..., T]) -> None:
self.wrapped: Callable[..., T] = wrapped
update_wrapper(self, wrapped) # type:ignore[arg-type]

def __get__(self, instance, obj_type=None):
@overload
def __get__(
self, instance: None, obj_type: Any = None
) -> "_lazy_property_and_property[T]":
...

@overload
def __get__(self, instance: object, obj_type: Any = None) -> T:
...

def __get__(
self, instance: object, obj_type: Any = None
) -> "T | _lazy_property_and_property[T]":
if instance is None:
return _lazy_property_and_property(self.wrapped)
with torch.enable_grad():
Expand All @@ -151,14 +166,14 @@ def __get__(self, instance, obj_type=None):
return value


class _lazy_property_and_property(lazy_property, property):
class _lazy_property_and_property(lazy_property[T], property):
"""We want lazy properties to look like multiple things.

* property when Sphinx autodoc looks
* lazy_property when Distribution validate_args looks
"""

def __init__(self, wrapped):
def __init__(self, wrapped: Callable[..., T]) -> None:
property.__init__(self, wrapped)


Expand Down
Loading
0