Home > Software design >  python function type mismatch
python function type mismatch

Time:08-19

I have defined the function as followed:

 def pick(l: list, index: int) -> int:
   return l[index]

It means then I must pass the integer parameter as the second argument. but when I use,

print(pick(['a', 'b', 'c'],True)) #returns me the 'b'.

The reason why I've moved from PHP to PYTHON is that PHP was a headache for me. (I mean not strongly typed variables, and also work with utf-8 strings).

How to restrict the passing boolean argument as an integer?

CodePudding user response:

Usually typing and a type checker configured on IDE should be enough. If you want to enforce typechecking at runtime, you can use the following:

if not isinstance(index, int):
    raise TypeError 

In Python though, bool is a subclass of int - isinstance(False, int) returns True. Which means TypeError will still not be raised. You could use

if isinstance(index, bool):
    raise TypeError 

but at that point I don't really see much reason to do so if programmer really wants to use such a construct - especially since based on language specification bool is an int, so should be accepted wherever int is - Liskov substitution principle

  • Related