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