Easy Q: dealing with object type

Erik Johnson spam at nospam.org
Wed Feb 2 20:52:16 EST 2005


    I quickly browsed through section 9 of the Tutorial, tried some simple
Google searches: I'm not readily seeing how to test class type.  Given some
object (might be an instance of a user-created class, might be None, might
be list, might be some other "standard" type object instance), how do you
test its type?


Python 2.2.2 (#1, Mar 17 2003, 15:17:58)
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...   pass
...
>>> obj = A()
>>> obj
<__main__.A instance at 0x81778d4>

# Here, it's fairly obvious its an A-type object. A as defined in module
'__main__'.

# Some of the comparisons against "Python primitives", work as you might
expect...
>>> int
<type 'int'>
>>> type(3) == int
1
>>> ls = range(3)
>>> ls
[0, 1, 2]
>>> type(ls)
<type 'list'>
>>> type(ls) == list
1
>>> type({}) == dict
1
>>> type(3.14) == float
1


# but this doesn't seem to extend to user-defined classes.
>>> dir(obj)
['__doc__', '__module__']
>>> obj.__module__
'__main__'
>>> type(obj)
<type 'instance'>
>>> type(obj) == A
0
>>> type(obj) is A
0

# The following "works", but I don't want to keep a set of instances to
compare against
>>> obj2 = A()
>>> type(obj) == type(obj2)
1






More information about the Python-list mailing list