给模块mymodule
和一个__init__.py
文件,如何从该文件中的另一个函数定义mymodule的函数?
__init__.py
代码大纲:
def a():
THISMODULE.__dict__["b"] = lambda: print("this is not weird")
a()
b() # Expect "this is not weird" output
mymodule
替代了anothermodule
,我想使代码更改像将import anothermodule as thething
替换为import mymodule as thething
一样简单。由于我还没有实现anothermodule
的所有功能,因此我想向用户发送有关它的通知,而不是使它崩溃并显示为“未定义”。
答案 0 :(得分:1)
__name__
是由导入机制设置的模块属性,其计算结果为当前模块的名称。将此添加到文件顶部:
import sys
THISMODULE = sys.modules[__name__]
其余的应该可以正常工作。