In a code, I am trying to check the type of a class of a variable entered into a function. What I want is something like this:
def foo(x):
if type(x)=='int':
pass
But I can't find anything that I can put in place of 'int' that will return True when I input an integer. I have made a temporary fix by doing type(x)==type(1), but I would like to know what to do to not use this sneaky trick.
Use int and isinstance():
if isinstance(x, int):
You could restrict yourself to just the type with:
if type(x) is int:
but that excludes subclasses of int.
However, ask yourself why you are testing for specific types; better to duck-type, and ask for forgiveness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With