Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Catch undefined module function calls and process it within the module

My my_module has just 1 function called f.

So

import my_module
my_module.f()

is a valid code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading