2

Consider the following code:

from typing import Optional

class Foo:
    def __init__(self):
        self.baz: Optional[int] = None

How do I find in code that baz has type Optional[int]? If I do type(Foo().baz), I only get None.

martineau
  • 119,623
  • 25
  • 170
  • 301
Johan de Vries
  • 175
  • 1
  • 9
  • `type` isn't how you access typing data anyway, it's in `__annotations__`. But I don't think annotations inside a method like that will get exposed anywhere; typically you'd included it in the parameter list, i.e. `(self, baz: Optional[int] = None)`, then it would be in `Foo.__init__.__annotations__`. – jonrsharpe Dec 04 '19 at 10:25
  • `mypy` finds them just fine, at least for init. I was hoping to be able to uses these as well in my code. – Johan de Vries Dec 04 '19 at 10:36

1 Answers1

4

You could define the instance attribute type in the class body, as described in the PEP

from typing import Optional, get_type_hints

class Foo:
    baz: Optional[int]

    def __init__(self):
        self.baz = None


get_type_hints(Foo)

Out[26]: {'baz': typing.Union[int, NoneType]}

Note that typing.Union[int, NoneType] is the same as Optional[int].

mcsoini
  • 6,280
  • 2
  • 15
  • 38