Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python `type(x)==` what?

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.

like image 613
ThisIsAQuestion Avatar asked Jan 17 '26 14:01

ThisIsAQuestion


1 Answers

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.

like image 119
Martijn Pieters Avatar answered Jan 20 '26 06:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!