python: how to identify the type of your variable

November 10th, 2007 mysurface Posted in Developer, python | Hits: 291819 | 20 Comments »

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'

20 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

  5. THANK YOU SOOOOOOO MUCH!!! for including how to find out what object a particular variable is. THANK YOU THANK YOU THANK YOU!!!

  6. [...] dictionary. I might be wrong about this, because I see something like this in django. Related Postspython: how to identify the type of your variable In python, every single variable is an object, every object must have a type, it is either data [...]

  7. Gibt es da noch Alternativen?

  8. This issue offers the lambent status which we onrush inaugurate the combat. This is stunning interesting lone and gives in-depth notification. Thanks as this grand article.

  9. I was just seeking this information for some time. After 6 hours of continuous Googleing, at last I got it in your web site. I wonder what’s the lack of Google strategy that don’t rank this kind of informative sites in top of the list. Generally the top web sites are full of garbage.

  10. @belly fat, google claims ‘+1′ may help to index the page, you may click the +1 on the post to help google rank this page.

  11. Have you ever considered including up additional videos to your weblog posts to hold the readers further entertained? I imply I simply learn by the entire piece of writing of yours and it was very first-class however since I am extra of a visible learner,I discovered that to turn into further useful nicely let me know the way it seems! I love what you might be always up too. Such vivid work and reporting! Continue the nice works guys I will add it to my blogroll.

  12. We’re a group of volunteers and starting a new scheme in our community. Your site offered us with valuable info to work on. You have done an impressive job and our whole community will be grateful to you.

  13. whoah this blog is magnificent i love reading your posts. Keep up the great work! You know, many people are looking around for this information, you could help them greatly.

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

    I believe it would be better to import types and do the following:

    type(d) is types.DictionaryTypes

    It will also work for modules, functions, ints, lists, etc.

  15. [...] http://linux.byexamples.com/archives/342/python-how-to-identify-the-type-of-your-variable/ python: how to identify the type of your variable [...]

  16. If some one needs to be updated with latest technologies afterward he must be
    pay a quick visit this web page and be up to date daily.

    Here is my weblog … mobile phone free gifts

  17. Hello mates, how is everything, and what you would like to say
    concerning this piece of writing, in my view its genuinely amazing for me.

    Here is my blog Casual Sex San Diego (Forest)

  18. It’s a pity you don’t have a donate button! I’d most certainly donate to
    this fantastic blog! I suppose for now i’ll
    settle for book-marking and adding your RSS fed to myy Google account.
    I look forward to brand new updates and will talk about this
    websie with my Facebook group. Talk soon!

  19. Thank you for your message.I’ll do the Italian translation for you, if you want Bye!

Leave a Reply