CodeQL 文档

“import *” 可能污染命名空间

ID: py/polluting-import
Kind: problem
Security severity: 
Severity: recommendation
Precision: very-high
Tags:
   - maintainability
   - modularity
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

使用 from xxx import * 导入模块时,模块中定义的所有公共名称都会被导入并绑定到 import 语句的局部命名空间。公共名称通过检查模块的 __all__ 变量来确定。如果 __all__ 未定义,则会导入模块中所有不以下划线开头的名称。这会使用不属于模块公共 API 的名称污染当前命名空间。

建议

解决此问题有两种方法:

  • 尽可能地修改被导入的模块,并定义 __all__ 来限制要导入的名称。

  • 否则,显式导入您需要的的值。

示例

以下简单示例展示了 __all__ 如何控制模块 finance 的公共名称。

# Example module - finance.py

__all__ = ['tax1', 'tax2']  #defines the names to import when '*' is used

tax1 = 5
tax2 = 10
def cost(): return 'cost'

# Imported into code using

from finance import *

print tax1
print tax2

如果 finance 模块不包含 __all__ 的定义,则可以使用 from finance import tax1, tax2 来替换 from finance import *

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私