Python

Whats the correct way to sort Python import x and from x import y statements

25 September 2026 · 5 min read

Whats the correct way to sort Python import x and from x import y statements

Python, renowned for its readability, hinges significantly on how you structure your code. A critical aspect of this is managing your import statements—those lines that bring external modules and packages into your script’s scope. But what’s the “correct” way to sort these imports? While Python doesn’t explicitly enforce a single rigid standard, best practices and conventions exist to enhance clarity and maintainability. This article delves into the intricacies of sorting import x and from x import y statements, providing actionable strategies to organize your Python code effectively.

PEP 8: The Foundation of Pythonic Imports

The gold standard for Python styling is PEP 8, a style guide that champions consistency and readability. It outlines a clear hierarchy for import statements, advocating for grouping and ordering them to improve code comprehension. Following PEP 8 helps other developers navigate your codebase seamlessly and reduces the risk of errors arising from misplaced or duplicated imports.

PEP 8 recommends grouping imports into three distinct sections, separated by blank lines:

  1. Standard library imports (e.g., os, sys, datetime)
  2. Related third party imports (e.g., requests, numpy, pandas)
  3. Local application/library specific imports

Within each group, imports should be sorted alphabetically. This practice makes it easy to locate specific imports and prevents accidental duplication.

Understanding import x vs. from x import y

The import x statement imports the entire module x, allowing access to its members using the dot notation (e.g., x.function()). Conversely, from x import y imports specific attributes (like functions, classes, or variables) directly into your current namespace, enabling you to use them directly (e.g., function()). Choosing between these two approaches depends on factors like the number of imports, potential naming conflicts, and code readability. If you only need a few specific attributes, from x import y can be more concise. However, for extensive usage of a module, import x often improves clarity by providing context through the module name prefix.

Alphabetical Order: The Key to Maintainability

Alphabetical sorting is the cornerstone of organized imports. It simplifies searching for specific modules and prevents accidental re-imports, which can lead to subtle bugs. Consistent alphabetical order enhances maintainability by making it easy for any developer to add, remove, or update imports without disrupting the existing structure.

Consider this example:

import sys import os from datetime import datetime import requests import pandas import numpy 

Here, the imports are neatly grouped and alphabetized within each group, making them easy to navigate.

Tools for Automated Import Sorting

Managing imports manually can be tedious, especially in larger projects. Fortunately, tools like isort automate this process, enforcing consistent import sorting across your codebase. isort integrates seamlessly with most code editors and build systems, freeing you to focus on writing logic, not sorting imports.

Other tools, such as linters like flake8 and pylint, can also identify and flag import-related issues like unused or missing imports, contributing to cleaner and more efficient code.

Practical Example: Building a Web Scraper

Imagine building a web scraper using requests and BeautifulSoup. Your imports might look like this:

import requests from bs4 import BeautifulSoup import re import os from datetime import datetime import json 

With proper sorting, they become:

import os import re from datetime import datetime import json import requests from bs4 import BeautifulSoup 

This improved structure immediately clarifies dependencies and makes maintaining the code easier.

Placeholder for infographic illustrating import sorting best practices.

Frequently Asked Questions (FAQ)

Q: Why is sorting imports important?

A: Sorting imports improves code readability, maintainability, and helps prevent errors due to duplicated or misplaced imports.

Managing your Python imports effectively is a cornerstone of writing clean, maintainable, and collaborative code. By adhering to PEP 8’s guidelines and leveraging automated tools, you can streamline your development workflow and contribute to a more robust and understandable codebase. Explore more about Python best practices on this helpful resource. Dive deeper into Python’s module system through the official documentation (https://docs.python.org/3/tutorial/modules.html) and learn about advanced import techniques. For best practices in code style, refer to PEP 8 directly (https://peps.python.org/pep-0008/imports). Start implementing these strategies today to elevate your Python code to a new level of organization and professionalism.

Question & Answer :
The python style guide suggests to group imports like this:

Imports should be grouped in the following order:

  1. standard library imports
  2. related third party imports
  3. local application/library specific imports

However, it does not mention anything how the two different ways of imports should be laid out:

from foo import bar import foo 

There are multiple ways to sort them (let’s assume all those import belong to the same group):

  • first from..import, then import

    from g import gg from x import xx import abc import def import x 
    
  • first import, then from..import

    import abc import def import x from g import gg from x import xx 
    
  • alphabetic order by module name, ignoring the kind of import

    import abc import def from g import gg import x from xx import xx 
    

PEP8 does not mention the preferred order for this and the “cleanup imports” features some IDEs have probably just do whatever the developer of that feature preferred.

I’m looking for another PEP clarifying this or a relevant comment/email from the BDFL (or another Python core developer). Please don’t post subjective answers stating your own preference.

Imports are generally sorted alphabetically and described in various places besides PEP 8.

Alphabetically sorted modules are quicker to read and searchable. After all, Python is all about readability. Also, it is easier to verify that something is imported, and avoids duplicate imports.

There is nothing available in PEP 8 regarding sorting. So it’s all about choosing what you use.

According to few references from reputable sites and repositories, also popularity, Alphabetical ordering is the way.

for e.g. like this:

import httplib import logging import random import StringIO import time import unittest from nova.api import openstack from nova.auth import users from nova.endpoint import cloud 

OR

import a_standard import b_standard import a_third_party import b_third_party from a_soc import f from a_soc import g from b_soc import d 

Reddit official repository also states that In general PEP-8 import ordering should be used. However, there are a few additions which are that for each imported group the order of imports should be:

import <package>.<module> style lines in alphabetical order from <package>.<module> import <symbol> style in alphabetical order 

References:

PS: the isort utility automatically sorts your imports.