Detecting a new style class

Graham Ashton gashton at cmedltd.com
Tue Apr 23 04:53:14 EDT 2002


Hi. I've got some code tha only works properly for classic classes.
Before I get round to fixing it, I'd like to put some protection in
place to prevent it from being used with a new style class.

This means that I'd like to be able to detect whether my class is being
subclassed by a new or classic class. To do that I'm testing self to see
if it has a __new__ attribute. Is there a better way to do it?

I find that the behaviour varies depending on the order in which a
class's super classes are defined. In the example below, I'd like the
instantiation of class B to throw the same RuntimeError as A:

Python 2.2 (#2, Mar 11 2002, 13:24:00) 
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from AbstractSingleton import AbstractSingleton
>>> class A(AbstractSingleton, object):
...   pass
... 
>>> a = A()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "AbstractSingleton.py", line 60, in __init__
    self.__check_for_new_style_class()
  File "AbstractSingleton.py", line 66, in __check_for_new_style_class
    raise RuntimeError, "New style classes are not supported"
RuntimeError: New style classes are not supported
>>> class B(object, AbstractSingleton):
...   pass
... 
>>> b = B()
>>> 

Thanks.

-- 
Graham Ashton






More information about the Python-list mailing list