Why does `type(myField)` return “ and not “?

in python 2, all of your classes should inherit from object. If you don’t, you end up with “old style classes”, which are always of type classobj, and whose instances are always of type instance.

>>> class myField():
...     pass
... 
>>> class yourField(object):
...     pass
... 
>>> m = myField()
>>> y = yourField()
>>> type(m)
<type 'instance'>
>>> type(y)
<class '__main__.yourField'>
>>> 

If you need to check the type of an old-style class, you can use its __class__ attribute, or even better, use isinstance():

>>> m.__class__
<class __main__.myField at 0xb9cef0>
>>> m.__class__ == myField
True
>>> isinstance(m, myField)
True

But… you want to know the type of the argument passed to your class constructor? well, that’s a bit out of python’s hands. You’ll have to know just what your class does with it’s arguments.

Leave a Comment

tech