Skip to content Skip to sidebar Skip to footer

Check Whether The Type Of A Variable Is A Specific Type In Python

I want to check whether the type of a variable is a specific kind in Python. For example- I want to check if var x is an int or not. >>x=10 >>type(x)

Solution 1:

Use the isinstance() function to test for a specific type:

isinstance(x, int)

isinstance() takes either a single type, or a tuple of types to test against:

isinstance(x, (float, complex, int))

would test for a series of different numeric types for example.

Solution 2:

Your example could be written as:

iftype(10) is int: # "==" instead of "is" would also work.
    print'yes'

But note that it might not exactly do what you want, for example, if you wrote 10L or a number greater than sys.maxint instead of just 10, this would not print yes, because long (which would be the type of such a number) is not int.

Another way is, as Martijn already suggested, to use the isinstance() builtin function as follows:

ifisinstance(type(10), int):
    print'yes'

insinstance(instance, Type) returns True not only if type(instance) is Type but also if instance's type is derived from Type. So, since bool is a subclass of int this would also work for True and False.

But generally it is better not to check for specific types, but for for the features, you need. That is, if your code can't handle the type, it will automatically throw an exception when trying to perform an unsupported operation on the type.

If you, however, need to handle e.g. integers and floating-point numbers differently, you might want to check for isinstance(var, numbers.Integral) (needs import numbers) which evalutes to True if var is of type int, long, bool or any user-defined type which is derived from this class. See the Python documenation on the standard type hierarchy and [numbers module]

Solution 3:

You can use the following ways:

>>> isinstance('ss', str)
True>>> type('ss')
<class'str'>
>>> type('ss') == strTrue>>> 

int - > Integer

float -> Floating Point Value

list -> List

tuple -> Tuple

dict -> Dictionary

For classes it is a little different: Old type classes:

>>># We want to check if cls is a class>>>classA:
        pass
>>>type(A)
<type 'classobj'>
>>>type(A) == type(cls)  # This should tell us

New type classes:

>>># We want to check if cls is a class>>>classB(object):
        pass
>>>type(B)
<type 'type'>
>>>type(cls) == type(B)  # This should tell us>>>#OR>>>type(cls) == type# This should tell us

Post a Comment for "Check Whether The Type Of A Variable Is A Specific Type In Python"