CodeQL documentation

Use of a print statement at module level

ID: py/print-during-import
Kind: problem
Severity: recommendation
Precision: high
Tags:
   - reliability
   - maintainability
   - convention
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