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
?
Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.
This module supports type hints as specified by PEP 484 and PEP 526. The most fundamental support consists of the types Any , Union , Tuple , Callable , TypeVar , and Generic . For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.
In his excellent article The State of Type Hints in Python, Bernát Gábor recommends that “type hints should be used whenever unit tests are worth writing.” Indeed, type hints play a similar role as tests in your code: they help you as a developer write better code.
Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.
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:
from typing import Optional
...
self.some_attribute: Optional[AnotherClass] = None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With