Classic and New Style Classes?

Peter Otten __peter__ at web.de
Thu Jun 24 09:14:08 CEST 2004


Chris S. wrote:

> I'm generating the source of an object from a list of objects. Therefore
> I need to determine if the object is a class definition (i.e. 'def
> something(whatever):') or a class instance (i.e. 'somename =
> somethingelse()'). With classic classes this is trivial, since all I
> have to do is check the type. However, for the new "improved" style
> classes this seems next to impossible, since everything is essentially
> an instance of something.
> 
> isinstance(class, classinfo) won't work since I won't necessarily know
> classinfo.
> 
> Is there any way to make this distinction? Any help is appreciated.

It's not clear to me why isinstance() wouldn't work:

>>> import types
>>> def f(): pass
...
>>> class T(object): pass
...
>>> class U: pass
...
>>> isinstance(T(), types.FunctionType)
False
>>> isinstance(U(), types.FunctionType)
False
>>> isinstance(f, types.FunctionType)
True

Another option would be to use callable(), which also returns True for
classes and callable instances:

>>> class V(object):
...     def __call__(self): pass
...
>>> callable(T)
True
>>> callable(T())
False
>>> callable(V())
True

Peter




More information about the Python-list mailing list