What is the point of defining the type of an argument in a function in python?

Asked

Viewed 18 times

1

I imagined that previously defining the type of argument in a function in python would automatically cause the program to return a Typeerror if the user added an argument with different typing than the one expected by the function.

However, I noticed that adding the type of the object doesn’t change the behavior of the function in this aspect (and it doesn’t seem to change anything, actually).

Example:

def user_sum(L:list):
    if len(L)==1:
        return L[0]
    else:
        return L[0]+user_sum(L[1:])

print(user_sum(15))

Returns:

Traceback (most recent call last):
  File "/home/lucas/projects/frontends/recursion/sum_rec.py", line 7, in <module>
    print(user_sum(15))
  File "/home/lucas/projects/frontends/recursion/sum_rec.py", line 2, in user_sum
    if len(L)==1:
TypeError: object of type 'int' has no len()

This is exactly the same error that would return if you had not specified the object type. Therefore, what is the point of defining the type of argument in a function beforehand?

  • 1

    I marked the duplicates above because I understand that their answers already cover their questions. If this is not the case, just [Dit] the question and say which specific point has not been covered by the other questions

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.