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