module not callable - why not?
Bengt Richter
bokr at oz.net
Tue Apr 20 13:25:40 EDT 2004
On Tue, 20 Apr 2004 12:42:44 GMT, Michael Hudson <mwh at python.net> wrote:
>Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
>
>> And yet, you can call a class instance if it has a __call__
>> operation defined. I don't see why modules shouldn't be the same.
>
>Well, for a possible counter argument, consider that you can only call
>an instance of a new-style class if the CLASS defines the __call__
>method...
>
ISTM you could give the module class a __call__ property, so you could
customize the callability of module instances something like:
>>> print '----\n%s----'% file('callablinst.py').read()
----
class Callablinst(object):
def _getcallable(self): return self.__dict__['__call__']
def _setcallable(self,v): self.__dict__['__call__'] = v
__call__ = property(_getcallable, _setcallable)
----
>>> from callablinst import Callablinst as CI
>>> c = CI()
>>> c()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "callablinst.py", line 2, in _getcallable
def _getcallable(self): return self.__dict__['__call__']
KeyError: '__call__'
>>> c.__call__ = lambda:'I am callable now ;-)'
>>> c()
'I am callable now ;-)'
>>> c2 = CI()
>>> c2()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "callablinst.py", line 2, in _getcallable
def _getcallable(self): return self.__dict__['__call__']
KeyError: '__call__'
>>> c2.__call__ = lambda:'I am c2'
>>> c2()
'I am c2'
UIAM, a def __call__(whatever): ... somewhere in the global scope of such a
module's source should then be picked up (depending on how the execution of
the def actually does the function name binding perhaps -- presumably it would
either bypass the attribute/property mechanism, or would use it). Either way
I would guess subsequent use of the module as callable would pick up the function
bound to __call__, but I'm not certain.
Regards,
Bengt Richter
More information about the Python-list
mailing list