Created
April 3, 2021 00:07
-
-
Save a-recknagel/bf44b50c216b10e5eb406a6aa19063eb to your computer and use it in GitHub Desktop.
How to include property annotations as if they were attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
def annotate_properties(_cls=None): | |
def wrap(cls): | |
properties = [(x, getattr(cls, x)) for x in dir(cls) if type(getattr(cls, x)) == property] | |
for name, property_ in properties: | |
cls.__annotations__[name] = property_.fget.__annotations__["return"] | |
return cls | |
# nifty pattern to make decorators work both with and without parens | |
if _cls is None: | |
return wrap | |
return wrap(_cls) | |
# order matters here, dataclass's code needs to run first | |
@annotate_properties | |
@dataclass | |
class Foo: | |
var: int | |
@property | |
def x(self) -> int: | |
return self.var + 2 | |
print(Foo(1).__annotations__) # {'var': <class 'int'>, 'x': <class 'int'>} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment