loading...

Type hints for variables in Python

pythonmeister profile image pythonmeister ・2 min read

One of the features in Python 3 I really like are the type hints.
These are described in PEP-484 and give you the possibility to annotate variables in Python with type information.
The type information is not enforced, but many tools and IDEs out there are capable of letting you know when your source code doesn't conform.
Here you can see using PyCharm this information:

Example in PyCharm

Python's type system is strong but dynamically typed. You can change the type of a variable at any time, but not all operands are defined for each combination of types.

But that makes professional software development a lot complexer:
Type information reduces guesses or the need for interpretation of the source code to figure out what might be the right content and it disables you from using code analysis.

So I started to use this feature a lot more, as now my IDE of choice can assist me in avoiding the most obvious errors.

Some examples (Python 3):

a: int = 10
b: int = 20
c: int = a + b

@dataclass
class Point:
    x: float
    y: float

p: Point = Point(3.14159, 2.714)

array_of_strings: [str] = ['Hello', 'World']

There is an accompanying module named typing, which offers a number
of additional classes and methods to do much more complex stuff.
For example, you can define compound type information for things like Points:

from typing import TypeVar, Dict
from math import sqrt
# create a type variance
T = TypeVar('T', int, float)
# define a Point as a dictionary consisting of a map from str to type 'T'
Point = Dict[str, T]


def distance(a: Point, b: Point) -> float:
    """return the euclidean distance between to points"""
    return sqrt((b['x'] - a['x'])**2 + (b['y'] - a['y'])**2)


print(distance({'x': 10, 'y': 10}, {'x': 20, 'y': 20}))

When you try do use Python dynamic type feature and take types which are not annotated, PyCharm gives you meaningful insights:

Example in PyCharm

If you want to know what happens when programming languages lack a sane type system, watch this:

Wat

P.S.: No, I don't dislike JavaScript. But I like TypeScript more.

Posted on by:

pythonmeister profile

pythonmeister

@pythonmeister

Senior DevOps with emphasis on Ops, Python fanatic, PostgreSQL lover.

Discussion

markdown guide