How can I dial a hint attribute in Python 3.5?

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

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

How to add a type hint so that the IDE understands what some_attributea type usually has AnotherClass?

+4
source share
2 answers

In Python 3.5 you need to write

self.some_attribute = None  # type: AnotherClass

Starting with Python 3.6, a new type of syntax has been added for variables ( PEP 526 ):

self.some_attribute: AnotherClass = None

This is likely to cause every type checking system to complain, because None is not really an instance of AnotherClass. Instead, you can use typing.Union[None, AnotherClass]either shorthand:

from typing import Optional
...
self.some_attribute: Optional[AnotherClass] = None
+5
source

- Python - , , , .

IDE - Pycharm. Specifying types of local variables and attributes - IDE , , ,

a = None #type: str

0

Source: https://habr.com/ru/post/1658426/


All Articles