Detecting a new style class

Alex Martelli aleax at aleax.it
Wed Apr 24 08:05:46 EDT 2002


<posted & mailed>

[Not following c.l.py these days, but thanks to lac for pointing this 
out!}:

Graham Ashton wrote:
        ...
> Okay, good point. I'm using the Alex's Borg pattern in place of a
> singleton, as shared state will do quite nicely. I'm also trying to
> protect myself from getting caught out by new style classes (in other
> words it doesn't work -- in general -- for classes derived from, for
> example, dict).

Right: Borg in its simplest incarnation is based on an instance's state
being all kept in its __dict__, and a new-style instance may have
per-instance state elsewhere (e.g. by subclassing list or dict).

> An alternative question would be -- does anybody know how to do the Borg
> so that it works for new style classes?

http://www.aleax.it/Python/5ep.html explores the issue a bit and
settles on automatic delegation (DeleBorg) as the most solid
solution.  I'm still not quite convinced that it's the best solution,
but if you cannot constrain the classes to be Borg-ized, it's hard
to think of another.

If you CAN constrain the classes in question, then I think that
checking for the metaclass is the right approach.  E.g. if you only
want to accept a class K that's a "classic class", that's the same
as saying that type(K) must be types.ClassType -- not the
builtin 'type', or something yet more devious.


Alex




More information about the Python-list mailing list