Callable modules
Why doesn't Python allow modules to have a __call__
method? (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
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 module. Specifically, code your mod_call.py
as follows:
import sys
class mod_call:
def __call__(self):
return 42
sys.modules[__name__] = mod_call()
Now your code importing and calling mod_call
works fine.
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.
https://docs.python.org/reference/datamodel.html#special-lookup