PEP 713: Callable Modules

You can make a module callable by setting its class to a subclass of types.ModuleType and implement the call in that subclass. I have an implementation of a function that makes a module callable and allows to set any function as the called function. You can even make stdlib modules callable (though I do not recommend doing that).
Here’s the file callmod.py:

import types

def make_module_callable(module, func=None):
    if func is None:
        func = getattr(module, '__call__', None)
    if not callable(func):
        raise ValueError("func should be a callable")

    class CallableModule(types.ModuleType):
        def __call__(clas, *args, **kargs):
            func(*args, **kargs)
    module.__class__ = CallableModule

and a module calltest.py to test it on:

def __call__(*args, **kargs):
    print(f"Module {__name__} was called with {args=} and {kargs=}")

And here is the result:

>>> from callmod import make_module_callable
>>> import calltest
>>> make_module_callable(calltest)
>>> calltest(6, 7, k='me')
Module calltest was called with args=(6, 7) and kargs={'k': 'me'}
>>> import os
>>> make_module_callable(os, print)
>>> os("Obscure", "print", "function")
Obscure print function
1 Like