限制Python导入的范围 [英] Limiting scope of Python import
问题描述
我有一些看起来像这样的代码:
I have some code that looks like this:
from pyparsing import Word, alphas, Optional, ...
# Do stuff ...
# And at the end, save a result to the outside world.
parser = ...
# Now use parser but don't use anything else from pyparsing again.
我喜欢调用from <package> import <etc>
的便利,但是我只希望将其用于很小的一段代码中.恐怕我为命名空间污染做出了贡献,因为在同一文件中有许多像这样的小片段.
I like having the convenience of calling from <package> import <etc>
, but I only want it to be used in a very small segment of code. I am afraid I am contributing to namespace pollution because I have a number of small snippets like this in the same file.
处理这种情况的Python方法是什么?我仍然只是在玩弄它,所以我宁愿不写和重写pyparsing.
这么多次.
What is the Pythonic way of handling this situation? I am still just kind of playing around with it, so I would rather not write and rewritepyparsing.
so many times.
推荐答案
一种简单的方法是使用函数作用域来控制文件中的导入可见性:
One easy way is to use function scope to control import visibility within a file:
def prepare_parser():
from pyparsing import Word, alphas, Optional, ...
# do stuff, and get the final thing to return
return ...
parser = prepare_parser()
这篇关于限制Python导入的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!