multi-Singleton-like using __new__
J Peyret
jpeyret at gmail.com
Sat Feb 9 01:24:15 EST 2008
On Feb 8, 5:38 pm, Freek Dijkstra <fr... at macfreek.nl> wrote:
If you want to subclass, my initial example did not cover that. This
will, or at least, I don't have any problems with similar code:
... def __new__(cls,uri,*args,**kwds):
... try:
... return cls.cache[(cls,uri)] #notice that I added the
class itself as a key.
... except KeyError:
... print "cache miss"
... res = cls.cache[(cls,uri)] = object.__new__(cls)
... return res
Your mileage apparently varies, but I'm still not sold on using a
metaclass. Just because it is a bit fancy for the requirements,
IMHO. Later you may have cached/singleton classes that really need a
metaclass for something else, with subclasses of _those_ that don't
want caching. That's definitely just my $.02 there, I don't
necessarily expect others to share my prejudices and misgivings.
Anyway, I should post answers more often - I learned more today than
by asking questions ;-) Txs all, for the has_key/in performance
pointers, they are exactly contrary to what I would have thought.
Cheers
More information about the Python-list
mailing list