def check_it(probe):
if probe is str:
return ("a string")
elif probe is int and probe > 100:
return ("large int")
else:
return ("small int")
print(check_it("hi"))
Asked
Active
Viewed 42 times
1

Morten Jensen
- 5,818
- 3
- 43
- 55

Kirigaya
- 19
- 3
-
Does this answer your question? [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) – wovano Nov 12 '21 at 14:38
-
the "is" operator is usually meant to check if item is None, It is not meant to replace == or proper type-checking – michaelgbj Nov 12 '21 at 14:56
-
`probe is int` is true for exactly one value of `probe` - which is `int`. Not *any* integer, the specific class `int`. – jasonharper Nov 12 '21 at 15:13
1 Answers
6
If you want to check if a Python object is e.g. an integer, call isinstance(obj, int)
.
if probe is int
does not work as you expect it to (is
checks object identity, not type).
Try something like this:
def check_it(probe):
if isinstance(probe, str):
return ("a string")
elif isinstance(probe, int) and probe > 100:
return ("large int")
else:
return ("small int")
Example outputs:
In [4]: check_it(42)
Out[4]: 'small int'
In [5]: check_it("42")
Out[5]: 'a string'
In [6]: check_it(4200)
Out[6]: 'large int'
Documentation/reference
https://www.w3schools.com/python/ref_func_isinstance.asp https://docs.python.org/3/library/functions.html#isinstance

Morten Jensen
- 5,818
- 3
- 43
- 55