tags:

views:

306

answers:

2
+2  Q: 

Callable modules

Why doesn't Python allow modules to have a __call__? (Beyond the obvious that it wouldn't be easy to import directly.) Specifically, why doesn't using a(b) syntax find the __call__ attribute like it does for functions, classes, and objects? (Is lookup just incompatibly different for modules?)

>>> print open("mod_call.py").read()
def __call__():
    return 42

>>> import mod_call
>>> mod_call()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> mod_call.__call__()
42
+4  A: 

Special methods are only guaranteed to be called implicitly when they are defined on the type, not on the instance. (__call__ is an attribute of the module instance mod_call, not of <type 'module'>.) You can't add methods to built-in types.

http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes

Miles
+9  A: 

Python doesn't allow modules to override or add any magic method, because keeping module objects simple, regular and lightweight is just too advantageous considering how rarely strong use cases appear where you could use magic methods there.

When such use cases do appear, the solution is to make a class instance masquerade as a method. Specifically, code your mod_call.py as follows:

import sys
class mod_call(object):
  def __call__(self):
    return 42
sys.modules[__name__] = mod_call()

Now your code importing and calling mod_call works fine.

Alex Martelli
Wow. I was seconds from posting a code example based on this example of yours: http://stackoverflow.com/questions/880530/can-python-modules-have-properties-the-same-way-that-objects-can/880550#880550
Stephan202
Heh, SO feels like a test of reflexes sometimes!-)
Alex Martelli
Thank you for the perspective, Alex.
gahooa