排除__builtin__模块

时间:2018-03-21 21:21:41

标签: python-3.x python-module built-in

Python中的__builtin__模块使开发人员命名空间混乱,其中包含许多具有非常通用名称的函数和类(例如maxsumid,{{1通常会妨碍命名变量的方式,当在上下文感知IDE之外时,可能会在不注意的情况下意外覆盖名称。

有没有办法阻止从某个文件隐式访问此模块并需要显式导入?

有些事情:

hash

我知道这是不好的做法。

1 个答案:

答案 0 :(得分:6)

您只需删除__builtins__,Python用于查找内置命名空间的名称:

In the js code:
InitialState: count = 0;
X called -> (count: prevState + 1);
Y called -> (count: prevState + 1);
Z called -> (count: 0 + 1); 

Meanwhile asynchronously:
InitialState: count = 0
X -> prevState=0, count = 0 + 1;
Y -> prevState=1, count = 1 + 1;
Z -> count = 1; then called again for (count: this.state.count + 1) which is now (count: 1 + 1)

警告:如果你在其他人的命名空间中这样做,他们会讨厌你。

  

...而且需要显式导入?

请注意,使用builtins解析import语句;)

>>> del __builtins__
>>> max
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'max' is not defined
  

...非常通用的名称(例如max,sum,id,hash等)经常妨碍命名变量,当在上下文感知IDE之外时,可能会意外覆盖名称而不会注意到

您只会创建一个隐藏名称的局部变量。如果你是在有限的范围内进行的话,这实际上是无关紧要的,尽管它仍然是糟糕的形式(可读性计数)。

>>> del __builtins__
>>> from builtins import max
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: __import__ not found

最佳实践:

  • 使用上下文感知编辑器,它会为您提供名称冲突的波浪线下划线,或
  • 使用Python的时间足够长,以便您熟悉内置名称(严重!)
  • 使用同义词(例如# this shadows built-in hash function in this namespace ... meh? hash = '38762cf7f55934b34d179ae6a4c80cadccbb7f0a' # this stomps built-in hash ... not a honking great idea! import builtins builtins.hash = lambda obj: -1 )或在名称上添加尾随下划线(例如checksum
  • ,避免名称隐藏