Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

‘import *’ may pollute namespace

ID: py/polluting-importKind: problemSecurity severity: Severity: recommendationPrecision: very-highTags:   - quality   - maintainability   - readabilityQuery suites:   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

When you import a module usingfromxxximport* all public names defined in the module are imported and bound in the local namespace of theimport statement. The public names are determined by checking the__all__ variable for the module. If__all__ is not defined then all names within the module that do not start with an underscore character are imported. This pollutes the current namespace with names that are not part of the public API for the module.

Recommendation

There are two ways to address this problem:

  • where possible, modify the module being importedfrom and define__all__ to restrict the names to be imported

  • otherwise, explicitly import the values that you need.

Example

The following simple example shows how__all__ controls the public names for the modulefinance.

# Example module - finance.py__all__=['tax1','tax2']#defines the names to import when '*' is usedtax1=5tax2=10defcost():return'cost'# Imported into code usingfromfinanceimport*printtax1printtax2

If thefinance module did not include a definition of__all__, then you could replacefromfinanceimport* withfromfinanceimporttax1,tax2.

References


[8]ページ先頭

©2009-2025 Movatter.jp