Skip to content

Instantly share code, notes, and snippets.

View Foxomax's full-sized avatar
:shipit:
Programming

Foxomax Foxomax

:shipit:
Programming
  • Nicaragua
  • 21:37 (UTC -06:00)
View GitHub Profile
@justinchuby
justinchuby / import_in_python.md
Last active January 29, 2026 03:46
Best practice for importing in Python

Best practice for importing in Python

1. Import at top level only

Allow imports at the module toplevel only, unless (1) it is too expensive to load the module or (2) module may not be available.

  • It is clear what a module needs when all imports are grouped in a single place. This makes refactoring easy.
  • Otherwise, any import errors will be raised only when the code executes. Erroneous imports may go undetected until the code path is hit at runtime.
  • Doing so reduces code duplication and improves consistency when we don't have the same import lines spread across the file.
  • Pylint has rule that checks for this: https://pylint.readthedocs.io/en/latest/user_guide/messages/convention/import-outside-toplevel.html