32

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

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

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

0

2 Answers 2

42

In Python 3.5, you have to write

self.some_attribute = None  # type: AnotherClass

Since Python 3.6, new type hinting syntax was 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:

self.some_attribute: AnotherClass | None = None
3

Python 3.10+ uses pipe sign | which many languages use as the or operator (PEP 604) to denote Typing.Union.

So…

self.some_attribute: AnotherClass|None = None

More concise, no Typing import needed.

FWIW, generally 3.10 also does away with many built containers needing Typing imports: list[int], not List[int] (which still works).

Note: if using forward declarations, Optional["AnotherClass"] is still needed, pipe doesn't work.

Also pipe handles more than None, since it’s a shorthand for Typing.Union:

some_attribute: AnotherClass|YetAnotherClass|None

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.