[英]How do you avoid importing a modules imports? Can you dynamically generate `__all__` at runtime?
I'm working on a large project that imports a lot of stuff.我正在做一个进口很多东西的大型项目。 I have modules that import modules with
from... import *
, and I want to avoid polluting module level variables when doing that.我有使用
from... import *
导入模块的模块,并且我想在这样做时避免污染模块级变量。
For example:例如:
module A:模块 A:
import foobar
def foo():
pass
bar = 10
module B:模块 B:
from A import *
# here, foobar is present, but I don't want it to be.
Obviously, the solution is to use __all__
.显然,解决方案是使用
__all__
。 So now it looks like this:所以现在它看起来像这样:
module A:模块 A:
import foobar
def foo():
pass
bar = 10
__all__ = ["foo", "bar"]
module B:模块 B:
from A import *
# here, foobar is no longer present
But this is tedious and time consuming.但这是乏味且耗时的。
Is it possible to generate __all__
dynamically, at runtime, without explicitly typing out all of the functions/classes that I want to export in a list?是否可以在运行时动态生成
__all__
,而无需在列表中明确输入我要导出的所有函数/类?
yes, you can generate your __all__
list dynamically with the help of dir
是的,您可以在
dir
的帮助下动态生成__all__
列表
module A:模块 A:
import foobar
__exclude_from_all__=set(dir()) #everything prior to this line will be here
def foo():
pass
bar =10
#a second call to dir now will include everything we defined after the first one
#and can be used to filter out the undesired stuff
__all__ = [ x for x in dir() if not (x.startswith("_") or x in __exclude_from_all__) ]
del __exclude_from_all__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.