Use of a print statement at module levelΒΆ
ID: py/print-during-import
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- quality
- reliability
- correctness
Query suites:
- python-security-and-quality.qls
Click to see the query in the CodeQL repository
Using print statements in level scope may result in surprising output at import time. This in turn means that other code cannot safely import the module in question if the program may only write real output to standard out.
RecommendationΒΆ
Replace the print statements with calls to some form of logging function or use the warnings module.
ExampleΒΆ
In the example, importing the module may cause a message to be printed, which may interfere with the operation of the program.
try:
import fast_system as system
except ImportError:
print ("Cannot import fast system, falling back on slow system")
import slow_system as system
#Fixed version
import logging
try:
import fast_system as system
except ImportError:
logging.info("Cannot import fast system, falling back on slow system")
import slow_system as system
ReferencesΒΆ
Python Language Reference: The print statement.
Python Standard Library: The print function.
Python tutorial: Modules.