Is there anything like Python export?

爱⌒轻易说出口 提交于 2019-12-04 04:18:57

First, import the module you want to export stuff into, so you have a reference to it. Then assign the things you want to export as attributes of the module:

# to xyz export a, b, c
import xyz
xyz.a = a
xyz.b = b
xyz.c = c

To do a wildcard export, you can use a loop:

# to xyz export *
exports = [(k, v) for (k, v) in globals().iteritems() if not k.startswith("_")]
import xyz
for k, v in exports: setattr(xyz, k, v)

(Note that we gather the list of objects to be exported before importing the module, so that we can avoid exporting a reference to the module we've just imported into itself.)

This is basically a form of monkey-patching. It has its time and place. Of course, for it to work, the module that does the "exporting" must itself be executed; simply importing the module that will be patched won't magically realize that some other code somewhere is going to patch it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!