PythonProgramming

Python Import Order Best Practices

Imports are the very first thing readers see in your Python files. A clean and consistent import order not only makes your code easier to read but also prevents subtle bugs and duplication.

Let’s break down the best practices for structuring imports in a Python file.

General Import Ordering

The widely adopted convention (including PEP 8) suggests the following order:

  1. Standard library imports
    • Built-in Python modules like os, sys, math.
  2. Related third-party imports
    • External packages installed via pip, like requests, numpy, pandas.
  3. Local application imports
    • Your own project files and modules.

Each group should be separated by a blank line for readability.

Python
# Standard library imports
import os
import sys
from datetime import datetime

# Third-party imports
import numpy as np
import requests
from flask import Flask

# Local application imports
from myproject.models import User
from myproject.utils import helper_function

Sorting Imports

Use alphabetical order within each group for consistency.

Python
# Correct
import os
import sys
Python
# Wrong
import sys
import os

Straight Imports First

All plain import package statements are listed first, then from … import … follows.
Inside each section, items are alphabetized.

PEP 8 (the official Python style guide) doesn’t mandate a strict order between them. But it’s better to list the straight import first for readability.

Python
# Standard library
import math
import os
import sys
from datetime import datetime
from pathlib import Path

Import in Separate Lines

Imports should usually be on separate lines:

Python
# Correct
import os
import sys
Python
# Wrong
import sys, os

It’s okay to say this though:

Python
# Correct
from subprocess import Popen, PIPE

Absolute Imports

Absolute imports are recommended, as they are usually more readable and tend to be better behaved or at least give better error messages.

Python
# Preferred
from myproject.utils import helper_function

However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose.

Python
# Only when necessary
from .utils import helper_function

Standard library code should avoid complex package layouts and always use absolute imports.

See also  Difference between variable declaration and definition in programming

Wildcard Imports

Avoid wildcard imports unless you’re working in interactive/debugging sessions. They pollute the namespace and make it unclear where functions/classes come from.

Python
# Correct
from math import sqrt
Python
# Wrong
from math import *

Import placements

PEP 8 states: imports should appear at the top of the file, just after:

  • Any module comments
  • Docstrings

And before:

  • Module globals
  • Constants
  • Functions/classes
Python
"""
This module demonstrates correct import placement.
"""

import os
import sys
from datetime import datetime

VERSION = "1.0"  # Module-level constant

def get_timestamp():
    return datetime.now().isoformat()

if __name__ == "__main__":
    print(f"Script started at {get_timestamp()}")

Final Checklist

  • Imports always at the top of the file.
  • Separate imports into 3 groups: Standard libraryThird-partyLocal imports.
  • Separate groups with blank lines.
  • Sort alphabetically.
  • Prefer absolute imports.
  • Imports first, then from-imports.
  • Avoid wildcard imports.
Most of the guidelines above (ordering, grouping, using absolute imports, avoiding wildcard imports, etc.) are best practices. They won’t break your code if not followed, but ignoring them can make your codebase messy, harder to maintain, and confusing for collaborators.

Leave a Reply

Your email address will not be published. Required fields are marked *