Callable modules
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.
As Miles says, you need to define the call on class level.
So an alternative to Alex post is to change the class of sys.modules[__name__]
to a subclass of the type of sys.modules[__name__]
(It should be types.ModuleType
).
This has the advantage that the module is callable while keeping all other properties of the module (like accessing functions, variables, ...).
import sys
class MyModule(sys.modules[__name__].__class__):
def __call__(self): # module callable
return 42
sys.modules[__name__].__class__ = MyModule
Note: Tested with python3.6.
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