A Data Scientist’s Guide to Python Typing: Boosting Code Clarity | by Egor Howell | Jul, 2023


The importance of typing and how it can be carried in Python

Egor Howell

Towards Data Science

Photo by Pankaj Patel on Unsplash

By typing we are not referring to physically touching our keyboard, but rather the datatypes our variables (and functions) take on in our Python code!

Python inherently is a dynamic language, which means there is no formal requirement to declare what datatype our variables take on. For example, a variable may start as an integer but change to a string somewhere else in the code. This flexibility can often lead to errors during runtime that can be hard to debug.

Other languages are statically typed, this means their variable types need to be explicitly declared and cannot change during runtime. If a variable is declared as an integer, it has to be an integer through the whole runtime of the program. Examples of statically typed languages are Fortran and C++.

However, in recent years Python has developed support for typing and nowadays it is an industry-wide standard. This is especially true for Data Scientists who need to deploy robust machine-learning models into production.

In this post, I want to take you through the basic syntax and processes behind typing in Python and how to use the mypy package, which allows us to seamlessly type check our code.

Typing is actually recommended as shown by PEP 484.

Let’s walk through a simple example to explain the need for type-checking in Python. Below we have a function that adds two numbers together called, ingeniously, adding_two_numbers:



Source link

Leave a Comment