My my_module has just 1 function called f.
So
import my_module
my_module.f()
is a valid code.
But I want to wrap undefined function calls the way my_module.f() is called instead. And I want to do it by default without any exta-code outside the module, i.e. I want to put all the wrapping code inside my_module. So when I do
import my_module
my_module.this_function_is_not_defined()
the python will not raise an exception, but call my_module.f() instead.
It’s kind of overriding __getattr__ of the class or __getitem__ of the dict.
Is it possible to do it within the module?
Kind of
globals().__getitem__ = lambda self, x: self.__getitem__ if self.__contains__(x) else f
>Solution :
You can set __getattr__ on a module just like on a class. Assuming that we have the following in my_module.py:
def f():
print('hello world')
def __getattr__(attr):
return f
We can use it like this:
>>> import my_module
>>> my_module.bar()
hello world
>>> my_module.this_function_is_not_defined()
hello world
Etc.