Type Annotations in Julia and Python

In Julia using type annotations is an integral part of writing Julia code. For Python however this is a fairly recent addition (version 3.5), which as of this writing (March 2019) has not been standardized. In Python they are referred to as type hints.

In Julia we would normally write a function incrementing an integer like this:

inc(a::Integer) = a + 1

This allows us to catch potential wrong usage of the function.

julia> inc(4)
5

julia> inc(nothing)
ERROR: MethodError: no method matching inc(::Nothing)
Closest candidates are:
inc(::Integer)

This has the benefit of catching the problem early on, where the function is called, rather than inside it. People doing C++ template programming will also be familiar with this problem. Type checking of generic types does not happen at the call site but inside the template function wherever the types don’t match up.

inc(a) = a + 1

Had I used this definition, the error would have been:

julia> inc(nothing)
ERROR: MethodError: no method matching +(::Nothing, ::Int64)
Closest candidates are:
+(::Any, ::Any, ::Any, ::Any...) at operators.jl:502
+(::Complex{Bool}, ::Real) at complex.jl:292
+(::Missing, ::Number) at missing.jl:93

So what we are seeing is that Julia is complaining about not finding a function call to satisfy nothing + 1

In Python this is quite different because type hints don’t do anything. Consider these two definitions of the increment function in python:

def inc(a: int) -> int:
return a + 1
def inc(a):
return a + 1

Using with an integer works fine of course.

python> inc(1)
2

Passing a None value gives this result regardless of whether you have used type hints or not:

python> inc(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in inc
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Essentially this works the same as when you define the function as inc(a) = a + 1 in Julia. The obvious question is why on earth does Python have type annotations then?

My investigation into this feature suggests that, it not created to assert on type at runtime, but rather to assist external tools, such as an IDE. IDE’s such as PyCharm can use the type hints to give better code completion recommendations.

Next we’ll look at string interpolation and string representations in Julia and Python.

Written by

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

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