Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Type annotation for __init__

What is the correct type annotation for a __init__ function in python?

class MyClass:
    ...

Which of the following would make more sense?

def __init__(self):
    # type: (None) -> None

def __init__(self):
    # type: (MyClass) -> MyClass

def __init__(self):
    # type: (None) -> MyClass

Since we would normally instantiate as myclass = MyClass(), but the __init__ function itself has no return value.

like image 570
hangc Avatar asked Oct 16 '17 21:10

hangc


People also ask

How do you annotate type in Python?

Python lists are annotated based on the types of the elements they have or expect to have. Starting with Python ≥3.9, to annotate a list, you use the list type, followed by [] . [] contains the element's type data type.

Should I use type annotations in Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

What are annotations Python?

Annotations were introduced in Python 3.0 originally without any specific purpose. They were simply a way to associate arbitrary expressions to function arguments and return values.

What is list from typing in Python?

List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.


1 Answers

self should be omitted from the annotation when it is given as a comment, and __init__() should be marked as -> None. This is all specified explicitly in PEP-0484.

like image 162
remram Avatar answered Oct 06 '22 21:10

remram