我有一些看起来像这样的代码:
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.
Run Code Online (Sandbox Code Playgroud)
我喜欢调用方便from <package> import <etc>,但我只想在很小的代码段中使用它.我担心我会对命名空间污染做出贡献,因为我在同一个文件中有很多像这样的小片段.
什么是Pythonic处理这种情况的方法?我仍然只是在玩它,所以我宁愿不写这么多pyparsing.次.
Ray*_*ger 11
控制命名空间污染的常用方法是
这些技术都由标准库中的核心开发人员使用.例如,十进制模块:
从私人名称导入开始,如import math as _math等.
后来它的工作,以建立一个线程环境之后变量删除使用del sys, MockThreading.
此外,它定义了一个__all__变量,以明确公共API是什么.
总之,这些技术使命名空间像吹口哨一样干净.
一种简单的方法是使用函数范围来控制文件中的导入可见性:
def prepare_parser():
from pyparsing import Word, alphas, Optional, ...
# do stuff, and get the final thing to return
return ...
parser = prepare_parser()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2768 次 |
| 最近记录: |