__call__ considered harmful or indispensable?
Carl Banks
pavlovevidence at gmail.com
Thu Aug 2 22:28:31 EDT 2007
On Aug 2, 2:30 pm, s... at pobox.com wrote:
> I'm wondering, are there some general cases where __call__ methods of
> a user-defined class are simply indispensable?
Indispensable's a strong word, but one thing that entails calling
syntax, and can't (reasonably) be done with closures is to override a
base class's __call__ method.
There is one notable type in Python that defines __call__ and that you
might want to subclass, namely type itself. So using __call__ is
indispensible for some metaclasses.
Here's my little example. I'm sure people could work out ways to do
it without __call__ or even a metaclass, but I doubt it'd be so
concise and out of the way as this:
class CachedResourceMetaclass(type):
def __init__(self,name,bases,clsdict):
super(CachedResourceMetaclass,self).__init__(name,bases,clsdict)
self._cache = {}
self._releasefunc = self.release
def decref(obj):
obj._refcount -= 1
if obj._refcount <= 0:
del self._cache[obj._key]
obj._releasefunc()
self.release = decref
def __call__(self,*args):
obj = self._cache.get(args)
if obj is not None:
obj._refcount += 1
else:
obj = super(CachedResourceMetaclass,self).__call__(*args)
obj._key = args
obj._refcount = 1
self._cache[args] = obj
return obj
Carl Banks
More information about the Python-list
mailing list