Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting not generating error for wrong type when running the code

I was recently checking about type hinting and after reading some theory I tried a simple example:

def myfun(num1: int, num2: int) -> int:
    return str(num1) + num2


a = myfun(1, 'abc')
print(a)
# output -> 1abc

Here you can see that I have defined num1 and num2 of type int and even after passing num2 value as string it is not generating any error.

Also the function should expect to return int type value but it's not complaining on returning string type value.

Can someone please explain what's going wrong here?

like image 252
Paritosh Mahale Avatar asked Sep 12 '25 07:09

Paritosh Mahale


1 Answers

It's called type hinting for a reason: you're giving a hint about what a variable should be to the IDE or to anyone else reading your code. At runtime, the type hints don't actually mean anything - they exist for documentation and usability by other developers. If you go against the type hints, python won't stop you (it assumes you know what you're doing), but it's poor practice.

Note that this differs from statically-typed languages like Java, where trying to pass an argument that's incompatible with the function's definition will produce a compile-time error, and if you pass a differently-typed but compatible argument (e.g. passing a float to a function that expects an int) it will be automatically typecast.

Note that the code you've given will encounter a TypeError if the programmer uses it like they're supposed to, because int cannot be concatenated to a str. Your IDE or linter should be able to see this and give you a warning on that line, which it does based on the type hints. That's what the type hints are for - informing the behavior of the IDE and documentation, and providing a red flag that you might not be using a function in the intended way - not anything at runtime.

like image 148
Green Cloak Guy Avatar answered Sep 14 '25 19:09

Green Cloak Guy