排除 __builtin__ 模块
Exclude __builtin__ module
Python 中的 __builtin__
模块使开发人员命名空间混乱,其中包含许多函数和 类 具有非常通用的名称(例如 max
、sum
, id
, hash
等)经常妨碍命名变量,并且在上下文感知之外时 IDE 可能会在不注意的情况下意外覆盖名称。
有没有办法阻止从某个文件隐式访问此模块,而是需要显式导入?
大致如下:
from __builtins__ import hash as builtin_hash
hash = builtin_hash(foo)
我知道这是不好的做法。
您可以简单地删除 __builtins__
,名称 Python 用于查找 built-in 命名空间:
>>> del __builtins__
>>> max
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'max' is not defined
警告:如果你在别人的命名空间中这样做,他们会讨厌你。
...and require explicit imports instead?
请注意,导入语句是使用内置函数解析的;)
>>> del __builtins__
>>> from builtins import max
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: __import__ not found
... very generic names (e.g. max, sum, id, hash etc.) that often get in the way of naming variables and when outside of a context-aware IDE one can accidentally overwrite a name without noticing
您将只创建一个隐藏名称的局部变量。如果您在有限的范围内这样做,这实际上是相当无关紧要的,尽管它仍然是糟糕的形式(可读性很重要)。
# 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
最佳实践:
- 使用 context-aware 编辑器,它会在名称冲突时为您添加波浪形下划线,或者
- 使用 Python 的时间足够长,以至于您可以记住 built-in 的名字(说真的!)
- 通过使用同义词(例如
checksum
)或在名称后面附加下划线(例如 hash_
)来避免名称阴影
Python 中的 __builtin__
模块使开发人员命名空间混乱,其中包含许多函数和 类 具有非常通用的名称(例如 max
、sum
, id
, hash
等)经常妨碍命名变量,并且在上下文感知之外时 IDE 可能会在不注意的情况下意外覆盖名称。
有没有办法阻止从某个文件隐式访问此模块,而是需要显式导入?
大致如下:
from __builtins__ import hash as builtin_hash
hash = builtin_hash(foo)
我知道这是不好的做法。
您可以简单地删除 __builtins__
,名称 Python 用于查找 built-in 命名空间:
>>> del __builtins__
>>> max
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'max' is not defined
警告:如果你在别人的命名空间中这样做,他们会讨厌你。
...and require explicit imports instead?
请注意,导入语句是使用内置函数解析的;)
>>> del __builtins__
>>> from builtins import max
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: __import__ not found
... very generic names (e.g. max, sum, id, hash etc.) that often get in the way of naming variables and when outside of a context-aware IDE one can accidentally overwrite a name without noticing
您将只创建一个隐藏名称的局部变量。如果您在有限的范围内这样做,这实际上是相当无关紧要的,尽管它仍然是糟糕的形式(可读性很重要)。
# 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
最佳实践:
- 使用 context-aware 编辑器,它会在名称冲突时为您添加波浪形下划线,或者
- 使用 Python 的时间足够长,以至于您可以记住 built-in 的名字(说真的!)
- 通过使用同义词(例如
checksum
)或在名称后面附加下划线(例如hash_
)来避免名称阴影