[英]how to create top-level module function from another function?
Given a module mymodule
with an __init__.py
file how can I define a functions of mymodule from another function within that file?给定一个带有__init__.py
文件的模块mymodule
,我如何从该文件中的另一个 function 定义 mymodule 的函数?
__init__.py
code outline: __init__.py
代码大纲:
def a():
THISMODULE.__dict__["b"] = lambda: print("this is not weird")
a()
b() # Expect "this is not weird" output
mymodule
comes as a replacement for anothermodule
and I want to make the code change as simple as replacing import anothermodule as thething
with import mymodule as thething
. mymodule
是anothermodule
的替代品,我想让代码更改像用import mymodule as thething
import anothermodule as thething
简单。 Since I don't implement all the functions of anothermodule
just yet, I would like to send the user a notification about it instead of crashing with "not defined".由于我还没有实现anothermodule
的所有功能,我想向用户发送有关它的通知,而不是因“未定义”而崩溃。
__name__
is a module attribute set by the import machinery, which evaluates to the name of the current module. __name__
是由导入机制设置的模块属性,其计算结果为当前模块的名称。 Adding this to the top of your file:将此添加到文件的顶部:
import sys
THISMODULE = sys.modules[__name__]
And the rest of what you already have should work correctly.并且您已经拥有的 rest 应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.