Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 415
akvilas Avatar asked Oct 21 '16 10:10

akvilas


People also ask

How do you type hint in Python?

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.

Does Python 3.6 support type hints?

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.

Should I type hint in Python?

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.

How do you use attributes in Python?

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.


1 Answers

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
like image 158
L3viathan Avatar answered Sep 20 '22 04:09

L3viathan