module with __call__ defined is not callable?

Scott David Daniels scott.daniels at acm.org
Thu Feb 9 08:29:48 EST 2006


Kent Johnson wrote:
> Antoon Pardon wrote:
>> This make me wonder. Would it be possible to do something with
>> metaclasses so that after
>>
>>      class SomeClass(MetaClass):
>>         ...
>>
>> SomeClass() will be equivalent to MetaClass.__call__(SomeClass)
> 
> I think that's already what happens. IIUC type.__call__ implements the 
> standard class creation calling __new__ and __init__.

You are a layer of abstraction off.
     class SomeClass(MetaClass):
         ...
creates a subclass of MetaClass, (the superclass of SomeClass).
SomeClass is still an instance of type (assuming new-style classes).

     class FunnyType(type):
         ...
defines a new metaclass, which can affect how instances of FunnyType
behave.

For a ridiculous example:
     class FunnyType(type):
         def __call__(self, *args, **kwargs):
             if 'please' in kwargs and kwargs['please']:
                 kwargs.pop('please')
                 return super(FunnyType, self).__call__(*args, **kwargs)
             print 'Nope, use your words:', args, kwargs

     class SomeClass:
         __metaclass__ = FunnyType

         def __repr__(self):
             print 'Lucky_%s' % id(self)

OK, now:
     v = SomeClass(please=True)
     print v
works, but
     v = SomeClass()
doesn't, nor does:
     v = SomeClass(please=False)

Think aboutwhat this code should do before running it, the mental
exercise is fun.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list