Live Chat!

python: how to identify the type of your variable

          0 votos

November 10th, 2007 mysurface Posted in Developer, python | Hits: 16545 |

In python, every single variable is an object, every object must have a type, it is either data structure or class instances. Python’s variable can be dynamically change easily during runtime, for example

>>> d={1:'one',2:'two'}
>>> print d
{1: 'one', 2: 'two'}
>>> d=['one','two']
>>> print d
['one', 'two']

First line d is declare as dict data type, and after 3rd line, d becomes list.

How to check whether d is dict or list?
You can either use type() or .__class__

>>> type(d)
<type 'list'>
>>> print d.__class__
<type 'list'>

How to check the type using if statement?
I want to check the type during runtime, not at interactive python shell.

d={}
if type(d).__name__=='dict':
     print 'Its dict!'
else:
     print 'Its not dict'

or this works too.

d={}
if type(d)==type(dict()):
     print 'Its dict!'
else:
     print 'Its not dict'

If an object is an instant of a class, it will be tricky. Let say we have define a class call myclass. Instantiate c as an object of myclass.


class myclass():
     pass

c=myclass()
>>> type(c).__name__
'instance'

Type(c) will gives result ‘instance’, telling you that this object is an instance of a class. I am more interested to find out what class an object instantiate from, so I do this:


if c.__class__.__name__==myclass.__name__:
      print 'c is an instant of myclass'
else:
      print 'c is something else'

Or something like that,


if type(c).__name__=='instance':
     if c.__class__.__name__=='myclass':
             print 'its from myclass'

4 Responses to “python: how to identify the type of your variable”

  1. You might want to check out isinstance()

    >>> d = {}
    >>> isinstance(d, dict)
    True
    >>> isinstance(d, int)
    False
    >>> class MyClass():
    … pass

    >>> c = MyClass()
    >>> isinstance(c, MyClass)
    True

  2. anon: Thx, this is what I looking for.

  3. > “every single variable is an object”

    if “variable” is d in print d, perhaps it can be rephrased as “a variable is a name for an object”, since an object has one unique id but can have several name.

  4. Hi, good blog!
    Saluti dall’Italia!
    By
    Francesco

Leave a Reply