捕获未定义的模块函数调用并在模块内处理它

huangapple go评论69阅读模式
英文:

Catch undefined module function calls and process it within the module

问题

我的 my_module 只有一个名为 f 的函数。

所以

import my_module
my_module.f()

是有效的代码。

但我想要以类似 my_module.f() 被调用的方式包装未定义的函数调用。并且我想要默认地在模块内部完成,不需要任何额外的代码,也就是说,我想要将所有的包装代码放在 my_module 内部。所以当我执行以下操作时:

import my_module
my_module.this_function_is_not_defined()

Python 不会引发异常,而是调用 my_module.f()

这有点像覆盖类的 __getattr__ 或字典的 __getitem__

在模块内部是否有可能实现这个功能?

类似于

globals().__getitem__ = lambda self, x: self.__getitem__ if self.__contains__(x) else f
英文:

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

答案1

得分: 2

你可以在模块上设置__getattr__,就像在类上设置一样。假设我们在my_module.py中有以下内容:

def f():
    print('hello world')

def __getattr__(attr):
    return f

我们可以这样使用它:

>>> import my_module
>>> my_module.bar()
hello world
>>> my_module.this_function_is_not_defined()
hello world

等等。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月7日 08:20:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76633226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定