Make Your Python Functions Readable with PEP 3107

A standardized type annotation for all your Python functions

Wouter van Heeswijk, PhD
Geek Culture

--

Image by Dariusz Sankowski via Pixabay

If there is one reason to prefer Python over other languages, it must be convenience. Its design philosophy makes coding no more complicated than it needs to be, relying on the common sense of its users. For instance, Python makes use of names that — under the hood — point to objects with interpreted types. Compare this to static-typed languages such as C++ or Java, which require to (tediously) declare a data type and value for each variable, then again when passing them as arguments to functions, while throwing errors for the slightest deviation. The duck typing approach adopted by dynamic languages such as Python often makes life a lot easier:

“If it looks like a duck and quacks like a duck, it’s a duck”

When it comes to legibility of functions, however, defining the expected input and output types might actually be a welcome feature. Fortunately such annotations can now be performed in Python with minimal effort — to be discussed in this article, obviously — but it was not always so.

Suppose we manage a warehouse, and frequently wish to check the stock levels of particular items. We store these levels in a list stock_levels that contains the…

--

--

Wouter van Heeswijk, PhD
Geek Culture

Assistant professor in Financial Engineering and Operations Research. Writing about reinforcement learning, optimization problems, and data science.