[Python Tips] Type Annotation

Python is a dynamic language that does not require you to specify data types as you create variables or supply return types. This makes development a lot easier but can introduce unexpected bugs when things don't go as expected.

Typed languages help prevent bugs by making sure strings are strings, and ints are ints when they need to be. This can save hours of debugging when suddenly something doesn't work when it used to in the past.

While Python doesn't require types, 3.5 added the option to specify a type. This allows Python IDE's like PyCharm and linters to provide better insight into your code and warn you of type misusage.

While the syntax in Python 3.5 works, it depended on comments which don't always display properly in different editors for this sort of thing. 3.6 took it further and added a specific syntax that displays better in editors that support it.

I will not cover the 3.5 Syntax as you should be using 3.6 if you are using Python 3.

Type Annotation in Python 3.6

In 3.5 you could type hint lists and dicts and this hasn't changed in 3.6.

No type hinting

employees = []

Type hinting

employees  = List[str]

The type hinting specifies a list of strings. Now nothing will stop you from putting an int or a float in there, everything will work perfectly fine but if your business logic expects strings and gets a float your code may break without any previous warning.

Using an IDE like PyCharms would have warned you that there was a float in your list of strings. You can also use mypy type checker or any number of code linters.

All the above code is compatible with 3.5, when we start dealing with variables that are not strings or dicts is when the syntax changes between 3.5 and 3.6. The below code only works with 3.6.

No type checking

employee = 'Bob'

Type checking

employee : str = 'Bob'

While this seems like a simple change, it can prove extremely useful when your code suddenly breaks for no apparent reason.

The syntax is simple

variable : [TYPE] = [VALUE]

The only change is adding a : and a [TYPE] to your variable declarations. You can verify the type with type(). If you are not using a code linter, I highly suggest you do. I will cover linting in a future post.

My Python Tips Series

H2
H3
H4
3 columns
2 columns
1 column
18 Comments
Ecency