Thursday, December 26, 2024
Google search engine
HomeLanguagesType Hints in Python

Type Hints in Python

Python is a dynamically typed language, which means you never have to explicitly indicate what kind of variable it is. But in some cases, dynamic typing can lead to some bugs that are very difficult to debug, and in those cases, Type Hints or Static Typing can be convenient. Type Hints have been introduced as a new feature in Python 3.5.

Using the mypy as a static type checker

pip install mypy

Python Type Hints

If we try to pass an integer to the function it works correctly. Now, if we try to pass a string to the factorial function, we will get an error, as we can’t do a mathematical comparison with string. Also, if we try to pass a floating point number, let’s say 5.01 we will also get an error here, as we are decrementing the number by 1 according to our logic in each iteration and it becomes -0.99 in the last iteration which returns “None”, which leads to an error as we are trying to multiply “None” with other floating point numbers.

Python3




# factorial function
def factorial(i):
if i<0:
 return None
if i == 0:
 return 1
return i * factorial(i-1)
 
# passing an integer to the function
print(factorial(4))
 
# passing a string to the function
print(factorial("4"))
 
# passing a floating point number to the function
print(factorial(5.01))


Output:

 

The Type-Hint is completely ignored by the Python interpreter. So, if we run this code again, we still get the same error. So, we have to use a static type checker that analyzes our code and tries to detect if we are violating our Type-Hints or not. The best known type checker is “mypy“. 

Python3




# factorial function
def factorial(i: int) -> int:
if i<0:
 return None
if i == 0:
 return 1
return i * factorial(i-1)
 
# passing a fraction to the function
print(factorial(5.01))


Output:

PS C:\Users\DELL> python ranking.py

 

To run the code now, we have to simply call the Python interpreter and we have to specify “-m” to indicate that we want to load a module and then specify the script which we want to check. For example: mypy program.py Now, if we run this it will not actually execute our “program.py” script but it will analyze it and will give us an error as like “Argument 1 to factorial has incompatible type float; expected int ” and which is a very clear message and that makes us much easier to debug our code as previously without mypy type checker the error message was not that much specific. And if we run the code again with an integer, it will work as fine.

PS C:\Users\DELL> mypy ranking.py

 

RELATED ARTICLES

Most Popular

Recent Comments