CodingZen — Static Typing in Python? No Way…

David Schaaf
Jun 27, 2018 · 11 min read

Static Typing? What does that even mean?!

Before I dive into this topic, let me take a step back and explain two foundational topics:

  1. Static typing v dynamic typing
  2. Strong typing v weak typing

Static Typing v Dynamic Typing

Static typing and dynamic typing describe when types are checked. Languages such as Java, C++ and C# check types before run-time, while languages such as Python and Go check types after run-time during the course of execution.

Weak Typed v Strongly Typed Languages

Another key dimension to consider is weakly typed v strongly typed, which (generally) describes what happens at compile time or runtime when it comes to type conversions and related errors. This is generally true as many languages have attributes of both or parts of each. For example, Python is considered a strongly typed language, but does not type checking at compile time, but does ensure that type errors are prevented at runtime. In contrast, a language like Java requires a declared type for all variables and type conversions generally require an explicit cast. Type checking is done at compile time.

Putting it All Together

In general, these concepts combined contribute to the overall type safety of the language or languages in question. Type safety has important implications that need to be considered. While this article is not intended to explore this topic in depth, let’s take a look at Python specifically in this context:

  1. Python is dynamically typed, which has three key implications:
  • Python is significantly less verbose than most statically typed languages
  • Developers can be much more productive as a result
  • However, errors are not caught at compile time, resulting in a hire risk of runtime errors

2. Python is strongly typed and has extra tools to further extend type checking, which has three key implications:

  • Type errors will occur at run-time even if they are not caught at compile time
  • However, not all type errors will be caught if proper enforcement is not in place
  • This can result in bugs that are difficult to track down. We will explore some later.

That’s a Lot to Take In! What Now?

The critical thing to remember is that Python comes with the “tools” to implement the appropriate degree of type checking. This is one of the reasons that Python is great for beginners and for analytics. You don’t have to use the features of Python that enable stronger type checking, but you can if you want to. You as the developer simply needs to make that choice and add the validation routines necessary to ensure type safety in your code.

The Newest Tool in the Toolbox

Python developers have always had tools to improve type safety such as explicitly using the type function or isinstance function. There have also been third party libraries at their disposal such as MyPy that helped to add static type checking into the mix, so errors could be detected before run-time. MyPy in particular has been incredibly successful and led to a critical change in Python 3.5: the addition of type hints in the core language. Another good option is to use PyCharm which uses type hints to perform real-time checks on your code.

What are type hints?

Type hints are essentially syntatic sugar that can be sprinkled on a function to “hint” at the type that the developer intended for either a function parameter or a return type. However, there are a couple of things to keep in mind:

  1. Type hints are not enforced. In other words, the Python language itself does nothing specific with the type hints in line with idea that thte developer should actually do the work if appropriate.
  2. Type hints can be added to existing code without impacting the ability for that code to run.

So if they are not enforced, why do they matter? For three reasons:

  1. By using type hints, you can make it much easier for others to understand your intentions.
  2. Type hints can be leveraged by third party tools, such as MyPy or Pyre to perform effective static type checking on your code before run-time.
  3. Instead of writing complex unit tests to test types, you can integrate MyPy and Pyre into your testing pipeline and also leverage both tools while you code.

With that in mind, let’s dive into some examples. All code uses Python 3.6+.

A Quick Example of Type Hints to Get You Started

To help you get started, let’s begin with a simple type hints example. The good news is that type hints are relatively intuitive to use. Here is an example:

On the surface this looks fine, but lets say that the year has to be an int for a downstream database or application. This could easily result in a hidden bug that may be difficult to pinpoint. To avoid this, we can add type hints to the function and leverage MyPy, Pyre, or other third party tools to validate our code is correct:

See the difference? Three things to point out:

  1. By adding “year: int”, we are now indicating that year must be an int.
  2. By adding “-> List[Any]” after the function parameters, we are now indicating that the results must be returned as a list.
  3. As a result, since the year in line 8 is passed as a string instead of an integer this should result in an error using MyPy.

And so it does! The screen shot below shows the error MyPy generates:

A More Detailed Example — The Cars Class

Let’s take this a step further with a more complex example. To test this out, we’ll use a cars class with a metadata method to print out the details of the class. Two things to note:

  1. Normally you might use the Python dunder methods such as __str__ and/or __repr__ to do this properly. You can find more details on this here.
  2. There are also better ways to set attributes on a class. In Python 3.7 for example, data classes are introduced, which seem to be a superior approach. Details can be found here.

The class below does not include type hints:

Note: Are you wondering what those “f”s are used for in the print statements in the car_metadata function? They represent a new approach to formatting strings in Python 3.6. Find out more details here.

Testing Out the CarsNoType Class

The code below is a simple way to test out the Cars class. Note that all the parameters are strings except for the year. If you run this code, it will run successfully as expected:

But the trouble is if you enter in the parameters to CarsNoType in the wrong order it will still run successfully, despite the fact the types are incorrect:

Implementing Type Hints

Type hints were an extensive addition to the Python language, so, even with this more detailed example, we will only scratch the surface here. With that said, it is easy to get started. Let’s rename the class CarsType to distinguish it and update the init method of our class by adding type hints to the function definition. Save the file as

Let’s deconstruct what is happening:

  1. Types have been added to each parameter using a colon followed by the type. As an example, “make” becomes “make: str”, indicating that the make is of type string.
  2. A return type has been added after the parameter list. In this case, there is no return type, so the return type is “None” as shown by “-> None”.
  3. Return None does not have to be specified in this case.

Testing Out Our Type Hints

Let’s first test out the modified class using the following code:

Wait? The code didn’t return any errors. What gives?!

Remember, Python doesn’t actually do anything with the type hints we have added, so we have to take an additional step to make this useful. Enter MyPy. MyPy is a tool that will leverage the type hints to perform static type checking, using the type hints as inputs. Before we can do that, let’s first install MyPy:

Depending on how Python 3 is installed on your system, you may need to change “python” to something else such as “python3”. MyPy also requires Python 3.4+ for reference.

Now that you have installed mypy, you can invoke mypy as follows:

You should see output similar to this:

This is a result of the following code from our test. Both the owner of the car and year the car was made are in the wrong place and thus have the wrong type:

Let’s take a minute to deconstruct the output from MyPy:

  1. — Refers to the line number within the carstype file. This may differ in your own file, but will help you track down the error.
  2. error: Argument 4 to “CarsType” has incompatible type “str”; expected “int” — This refers to the fact that “Daniel — wrong spot” was provided to the “Year” parameter which is an int according to our type hint.
  3. error: Argument 5 to “CarsType” has incompatible type “int”; expected “str” — This refers to the fact that “2018” was provided to the “Owner” parameter which is a str according to our type hint.

As you can see, this provides a much needed check for these scenarios and can help you avoid hidden bugs that can pop up later.

One Step Further — Checking Return Types

In our last example, we focused on the types of our function parameters and set the return type hint to None. However, this can be leveraged to enforce return types using mypy, including more complex types such as lists using the new typing library that was implemented along with type hints in Python 3.5. Here is the new class in it’s entirety from the file:

Notice that we have two functions in this case. The car_metadata function remains, but we have also added the car_metadata_error function to demonstrate how the return type hint can be used and enforced using MyPy. A couple of things to point out:

  1. The return type hint used in this case is “List[str]”. [str] represents the type that is expected within the list. In this case, I have updated the class so that all parameters are of str type for the sake of simplicity.
  2. In order to use complex types such as list, you must import “List” from the typing library using the line “from typing import List”.
  3. In cars_metadata_error, the function returns a tuple instead of a list. This should error out when we run MyPy.

So let’s test this out by adding the following code:

Then run MyPy as follows:

You should see output similar to this:

Notice that this error calls out that there is an “Incompatible return value”. This can be particular useful when you are heavily using properties throughout your Python classes, ensuring that you are returning the correct types in each case.

That’s great! How do I learn more?

As noted earlier, this just scratches the surface of type hints and how they can be used to improve the readability of your code and to implement static type checks. Here are some additional resources you can check out:

  1. Type Checking Python Programs with Type Hints and MyPy by Dan Bader —
  2. Type Hints in PyCharm —
  3. Deep Dive into Type Hints in PyCharm —
  4. MyPy Integration for Vim —
  5. Static Types for Python from PyCon 2017 (MyPy) —
  6. Pyre Performant Type Checking (Alternative to MyPy) —
  7. MonkeyType (for adding type hints to legacy code) —


Type hints are begging to be used in application development projects. Now that they are available, they may be overkill for data scientists and analysts, but are no doubt an essential new tool for software and data engineers. Static type checking has long been a missing piece in the puzzle for large scale Python projects and type hints are a step in the right direction that I am sure will continue to evolve in the coming years. In the meantime, it is prudent for most developers to add type hints to their code to improve readability and future proof code to be used with tools such as MyPy and Pyre. With libraries such as MonkeyType available to quickly update legacy code, it simple and straightforward to update entire python code bases with type hints, unleashing the full benefits of type hints and static type checking with little effort!

David Schaaf

Written by

Director, Data Engineering at Capital One that is Head of Product for Financial Services Data w/ a background in Product Mgmt, Python, data, & web-based apps.

David Schaaf

Written by

Director, Data Engineering at Capital One that is Head of Product for Financial Services Data w/ a background in Product Mgmt, Python, data, & web-based apps.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store