GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — ‘import *’ may pollute namespace — CodeQL query help documentation

‘import *’ may pollute namespace¶

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

Click to see the query in the CodeQL repository

When you import a module using from xxx import * all public names defined in the module are imported and bound in the local namespace of the import 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 imported from 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 module 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

If the finance module did not include a definition of __all__, then you could replace from finance import * with from finance import tax1, tax2.

References¶

  • Python Language Reference: The import statement.

  • Python Tutorial: Modules.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.