3

if i do something like this:

def f(x: str):
    pass

i can easily see this type hint for x if i do:

print(f.__annotations__)

however, i can't seem to figure out where the annotations live if i do something like this:

class C:
    def __init__(self):
        self.where_is_this_vars_annotation_stored: int = 4

does anyone know which __annotations__ dict contains where_is_this_vars_annotation_stored's type hint?

acushner
  • 9,595
  • 1
  • 34
  • 34
  • [`__annotations__` does not exist under class](https://docs.python.org/3/library/inspect.html#types-and-members). Perhaps there's a workaround for it. – r.ook Feb 26 '18 at 21:54
  • `__annotations__` does exist if you do something like `class C: i: int` – acushner Feb 26 '18 at 21:57
  • 1
    Interesting, perhaps I wasn't looking deep enough. It seems classes will create `__annotations__` to the mapping when there's annotated class attributes, but not for instance attributes which is what you're looking for. – r.ook Feb 26 '18 at 22:26

1 Answers1

0

i ended up writing something that uses inspect, ast, exec, and eval to solve this for me.

https://gist.github.com/sweettuse/f5fa022a0abadf3fc368105fcccc46c1

acushner
  • 9,595
  • 1
  • 34
  • 34