module with __call__ defined is not callable?
Scott David Daniels
scott.daniels at acm.org
Wed Feb 8 10:37:22 EST 2006
Steven D'Aprano wrote:
> On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote:
>
>> adam johnson wrote:
>>
>>> Hi All.
>>> I was wondering why defining a __call__ attribute for a module
>>> doesn't make it actually callable.
>> For the same reason that the following doesn't work
> [snip example]
>> The __call__ attribute must be defined on the class (or type) - not on
>> the instance. A module is an instance of <type 'module'>.
>
> 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.
You missed it. Steven D'Aprano was telling you why, and all you heard
was the no. He stated a more general principal which controls why
modules in particular are not callable. It is not a design decision
about modules; it is a design decision about classes and instances.
class SomeClass(object):
def __call__(self): return 'Text'
class AnotherClass(object):
def __repr__(self): return 'Missive'
name = SomeClass()() # this works
name = AnotherClass()() # this doesn't
obj = AnotherClass() # build an instance
def fun(*args): return 'more text' # *args so nearly any call works
obj.__call__ = fun # tack a function onto an instance
obj() # note this doesn't call the function.
Now, if you think the last _should_ do the call, then let's step
back to classes.
class SomeClass(object):
def __call__(self): return 'Text'
Now the SomeClass object (which is a subclass of object) has an
attribute named "__call__". Should that define how the expression
SomeClass()
is evaluated? Should that return the string 'Text' or create a
new instance of SomeClass?
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list