Dark theme

Type hints


While variables in Python have specific types (int; str; list; etc.), you don't have to tell Python what kind of thing you want to store in a variable; it works it out for you (type inference). Equally, when you pass arguments to a function you don't need to tell Python what kind of thing you're passing in. Python uses 'duck typing' (formally 'parametric polymorphism'): 'if it looks like a duck, and quacks like a duck, it can be treated as a duck' – that is, a function will work with anything passed to it, provided that thing has the functions and variables inside it that the function it is passed into uses. The disadvantage is that this allows for a particular type of bug, where you pass in something to a function that works, but isn't what you want; for example, say, after a long and complicated set of file readings we end up with var_a = "2" and want to use it thus (code: issue.py):
def add(a, b):
    return a + b

print(add(var_a, var_a))

For our input, this would print "22", as we've accidentally passed in strings where adding is concatenation, whereas what we probably wanted was var_a = 2, i.e. for the code to return 4. Some Python coders would suggest this flexibility for the function is a positive, and only complain when the function won't work because of the types passed in, as with:
print(add(range(2), range(2)))
but, frankly, these are the obvious issues; it's when code doesn't complain but does something quietly different you have to worry.

The alternative is manifest typing, where you have to explicitly say what kind of variables you're making when you make them. For example, here's some Java:
int varA = 10;
varA = varA + 5;
System.out.print(varA);

You also have to therefore say what kind of variables you're making for parameters in functions, along, usually, with the type of the thing returned:
int add(int varA, int varB) {
The advantage with this is that the system can do type checking: it can check that the type of thing passed in is correct. The disadvantage is that code becomes more complicated to write.

Generally, the lack of manifest typing in Python is good, but it is the kind of thing that makes people who write software that might accidentally kill someone or trash millions of pounds of investment very nervous about Python. Given this, Python 3.5 introduced "type hints" – a comment-like construction which outlines the type of variables Python uses more explicitly. They aren't used by Python, but can be checked by independent software to identify bugs.

The only issue with type hints is that you need to write extra code into your file to implement them, making them different from many debugging techniques, which tend to be independent of the code. Nevertheless, if you're going to write any software that might cause serious damage, they are worth implementing.