Last answered:

24 Feb 2022

Posted on:

24 Feb 2022

0

Resolved: Does type hint doesn't check arguments type?

Hi !
I have a doubt even if i have created a function with explicitly mentioning the type of argument needed for function, when I pass other type of args to function it works.
What is the point of type hint then ?

Let's say I have created a function :
def print_name(name:str) -> str :
   return f'My name is {name}'

so a function call with string argument -
print_name("Swarntam")
output => My name is Swarntam

and if I pass number instead:
print_name(110101)
output = > My name is 110101

Why is it taking numbers too as argument when I have declared the function to accept string with type hint ?

1 answers ( 1 marked as helpful)
Instructor
Posted on:

24 Feb 2022

1

Hey Swarntam,

Thank you for your question!

As Giles explains, type hints are only hints, nothing more. They do not affect the execution of the code in any way. Rather, they tell the person calling a certain function what kind of parameters this function expects and what it will return.

Type hints can be helpful when more than one person is working on the same project, or when you go back to a code you've written several years ago. You wouldn't need to remember the datatypes of each parameter, you have them as type hints. Of course, type hints are not the only way to document this. You can write comments or docstrings at the beginning of your functions, describing the expected datatype of each parameter.

To prevent a user from entering an incorrect datatype, you can either perform an if-else check at the beginning of the function, or enclose your code in a try-catch block.

As a final note, there exist Python libraries that make type hints more powerful such that they do affect the execution of the code, throwing an error if the incorrect datatype is entered.

Hope this answers your question!

Kind regards,
365 Hristina

Submit an answer