1

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?

Leo Garsia
  • 105
  • 1
  • 10
  • 2
    Python is not strongly typed either. You can check for the type inside the function and raise an error if it's the wrong type. – Guy Aug 18 '22 at 12:32
  • 1
    typically typing and a type checker configured on IDE should be enough, but if you want your code to reject that at runtime, you can use the following: `if not isinstance(index, int): raise TypeError` – matszwecja Aug 18 '22 at 12:37
  • @matszwecja Please type it as an answer and I will mark it as useful – Leo Garsia Aug 18 '22 at 12:42
  • @LeoGarsia Answered with some additional info because my comment might have been slightly incorrect. – matszwecja Aug 18 '22 at 12:51
  • @matszwecja I think that typing in python is formal. Since instead of an integer, the function returned a string without restriction. There is no need to declare types of variables. – Leo Garsia Aug 18 '22 at 18:09
  • 1
    @LeoGarsia Correct, typing is just a formality, and it has absolutely no bearing on code execution. But it exists so you can configure your IDE to do type checking based on those hints and *warn* you that you are passing/returning type different than specified. – matszwecja Aug 18 '22 at 19:46

1 Answers1

2

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

matszwecja
  • 6,357
  • 2
  • 10
  • 17