module with __call__ defined is not callable?

Bengt Richter bokr at oz.net
Fri Feb 10 19:03:57 EST 2006


On Thu, 9 Feb 2006 10:07:49 +1100, "Delaney, Timothy (Tim)" <tdelaney at avaya.com> wrote:

>Steven D'Aprano wrote:
>
>> That's not a _reason_, it is just a (re-)statement of fact. We know
>> that defining a __call__ method on a module doesn't make it callable.
>> Why not? The answer isn't "because defining a __call__ method on a
>> module or an instance doesn't make it callable", that's just avoiding
>> the question.=20
>
>My reading of the OP sounded like he wanted to know the *technical*
>reason for why it doesn't work - which is what I provided.
>
>If you can come up with a convincing argument, after re-reading the OP
>(as I've just done), that that is *not* what he meant, I'm all ears.
>
While you can't put __call__ on the builtin module type,
you _can_ put it on a subclass:

 >>> class M(type(__builtins__)):
 ...    def __call__(self): return '%r was called'%self
 ...
 >>> m = M('M')
 >>> m()
 "<module 'M' (built-in)> was called"

Not that I can see why the OP would want to spell any module access module().

OTOH, I could see wanting to define properties, and access module.latest_foo
and have it choose dynamically from versioned stuff, or something like that.
Of course you can write module.get_latest_foo() as an ordinary function, and
not be bothered with subclassing and jimmying sys.modules and such.

Properties and methods are both forms of descriptors, so they need to be attributes
of the type to work. With a subclass you could do that too.

Regards,
Bengt Richter



More information about the Python-list mailing list