Skip to content

Instantly share code, notes, and snippets.

@jacksmith15
Last active September 23, 2022 15:12
Show Gist options
  • Save jacksmith15/b8f5cd3f5b7945530c0006900556de65 to your computer and use it in GitHub Desktop.
Save jacksmith15/b8f5cd3f5b7945530c0006900556de65 to your computer and use it in GitHub Desktop.
Type annotations 101

Type Annotations

Full documentation is here.

Type annotations do not affect runtime, but allow other tools to statically analyse you code for errors. The offical checker is MyPy, which has an IntelliJ extension.

Variable annotations

Type annotations come after the variable/attribute declaration (unlike Java):

foo: int
foo = 1

They can be inline:

bar: int = 1

Function annotation

They can define the signature of functions:

def half(value: int) -> float:
    return value / 2

Annotation with generics

The typing module also exposes helpers for more complex annotations:

from typing import Any, Dict, Union

foo: Union[int, float] = 1  # `foo` can be an int or a float

dictionary: Dict[str, Any] = {"foo": 1, "bar": 2}  # dictionary is a `dict`, with string keys and values of any type

Attribute annotation

You can also annotate classes, and use them as annotations themselves:

class Foo:
    pass

class Bar:
    x: Foo  # This says that instances of Bar should have an attribute `x` of type `Foo`

Validating type annotations:

Type checkers can tell you if something is wrong, without running your code:

def foo(value: Union[str, None] = None) -> List[str]:
    return value.split("\n")

MyPy will show Item "None" of "Union[str, None]" has no attribute name "split" for the above code. With the editor extension, this will be highlighted as soon as you type it!

@GeraldineSmith1
Copy link

Useful and concise. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment