akvilas akvilas - 1 year ago 96
Python Question

How can I type hint an attribute in Python 3.5?

I have a class where I want the initial value of an attribute to be


class SomeClass:
def __init__(self):
self.some_attribute = None

How can I add type hinting, so that the IDE understands that
is usually of the type

Answer Source

In Python 3.5, you have to write

self.some_attribute = None  # type: AnotherClass

In Python 3.6, new type hinting syntax will be added for variables (PEP 526):

self.some_attribute: AnotherClass = None

This will probably make every type-checking system complain, because None is in fact not an instance of AnotherClass. Instead, you can use typing.Union[None, AnotherClass], or the shorthand:

from typing import Optional
self.some_attribute: Optional[AnotherClass] = None
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download