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.

Leave a Comment