Place all import statements at the top of the file as global imports rather than importing modules within functions or methods. Local imports reduce code readability, complicate dependency tracking, and can indicate poor code organization.
Place all import statements at the top of the file as global imports rather than importing modules within functions or methods. Local imports reduce code readability, complicate dependency tracking, and can indicate poor code organization.
Why this matters:
How to fix: Move all imports to the top of the file, organized in the standard order: standard library, third-party packages, then local modules.
Example:
# Bad - local imports
def _setup_runtime_dependencies(cls, logger, config, settings):
import os # Should be at top
import platform # Should be at top
if platform.system() == "Windows":
# ...
# Good - global imports
import os
import platform
def _setup_runtime_dependencies(cls, logger, config, settings):
if platform.system() == "Windows":
# ...
Exceptions: Local imports are acceptable only in rare cases like:
In such cases, add a comment explaining why the local import is necessary.
Enter the URL of a public GitHub repository