python function type mismatch

Question:

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?

Asked By: Leo Garsia

||

Answers:

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 intisinstance(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 and int, so should be accepted wherever int is – Liskov substitution principle

Answered By: matszwecja
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.