type classobj not defined?
Peter Otten
__peter__ at web.de
Wed Jan 3 12:14:42 EST 2007
Wesley Brooks wrote:
> Dear Users,
>
> I'm in the process of adding assert statements to a large piece of
> code to aid with bug hunting and came across the following issue;
>
> Using python in a terminal window you can do the following:
>
>>type(False) == bool
> True
>
> I would like to check that an object is a class, here's an example:
>
>>class b:
> ....def __init__(self):
> ........self.c = 1
> ....def d(self):
> ........print self.c
>
>>type(b)
> <type 'classobj'>
>
> But the following fails:
>
>>type(b) == classobj
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> NameError: name 'classobj' is not defined
>
> For the time being I'll use b.__name__ == b to ensure I'm getting the
> right class. Is there a reason why the other types such as bool are
> defined but classobj isn't?
No idea. You can easily define it yourself, though:
>>> class Classic: pass
...
>>> classobj = type(Classic)
>>> isinstance(Classic, classobj)
True
Note that "newstyle" classes (those deriving from object) are of type
'type', not 'classobj':
>>> class Newstyle(object): pass
...
>>> isinstance(Newstyle, classobj)
False
>>> isinstance(Newstyle, (classobj, type))
True
The inspect module wraps the functionality in a function:
>>> import inspect
>>> inspect.isclass(Newstyle)
True
>>> inspect.isclass(Classic)
True
Peter
More information about the Python-list
mailing list