["python","module","python-import"]
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
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