python: how to identify the type of your variable
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'
Live Chat!









November 10th, 2007 at 4:57 am
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
November 10th, 2007 at 7:40 am
anon: Thx, this is what I looking for.
November 11th, 2007 at 9:52 pm
> “every single variable is an object”
if “variable” is
dinprint 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.November 12th, 2007 at 11:25 pm
Hi, good blog!
Saluti dall’Italia!
By
Francesco