A person is engaged in programming

Python Isort: Streamlining Your Imports

Read Time:5 Minute, 42 Second

In the world of Python programming, as your projects grow in complexity, so do the number of files, lines of code, and dependencies. As you work on your projects, it’s common to import libraries as needed, resulting in a disorganized and sometimes chaotic import section in your codebase. Additionally, when collaborating with a team of engineers, each developer may have their own preferred import structure, leading to conflicting file versions in your repository.

To address these challenges, you can turn to isort, a Python utility and library that provides a systematic way of ordering imports in your Python projects.

What Is Isort?

Isort is a versatile tool that automatically sorts Python module imports in alphabetical order, categorizing them into different sections based on their type. This ensures that your import statements are not only organized but also consistent across your project. Isort is available both as a Command-Line Interface (CLI) utility and a Python library. Additionally, it offers plugins for various code editors, including Visual Studio Code and Sublime Text.

Sample Code File

Before diving into how to use Isort, let’s prepare a sample Python file to work with. We’ll intentionally mix up the order of imports and add some spacing to illustrate the difference between unsorted and sorted files. Here’s a sample unsorted Python code (main.py):

import pandas
import osimport sys
import numpy
from sklearn.linear_model import LinearRegressionfrom sklearn.linear_model import Ridge
from sklearn.linear_model import ElasticNet

Sorting Module Imports

Now that we have our Python file ready, let’s use Isort to sort the module imports neatly.

Sorting Module Imports in a Single Python File

If you have only one file that needs its module imports sorted (in our case, main.py), simply run the following command:

isort main.py

After running this command, the reformatted Python file will look like this:

import osimport sys
import numpyimport pandasfrom sklearn.linear_model import ElasticNet, LinearRegression, Ridge

As you can see, Isort has alphabetically sorted the import statements and organized them beautifully.

Sorting Module Imports in Multiple Python Files

If you want to sort the module imports in multiple Python files or across your entire Python project, execute the following command:

isort.

Isort will automatically identify all Python files within the directory and sort the module imports in each one.

A man is engaged in programming

Comparison Table 

Featureisortautopep8
PurposeImport sorting and formatting toolCode formatting tool with import sorting
Sorting MethodAlphabetical order, separated by typeAlphabetical order, separated by type
CLI Usageisort filename.pyautopep8 –in-place –aggressive –aggressive filename.py
IDE IntegrationSupported by various code editorsSupported by various code editors
Configuration OptionsExtensive configuration optionsLimited configuration options
Auto-fix ImportsYes, automatically fixes import orderYes, but less control over sorting preferences
PEP 8 ComplianceCompliant with PEP 8 guidelinesFocuses on general code formatting adherence
Community SupportActive community and regular updatesPart of the Pylint code quality tool

Please note that both isort and autopep8 are valuable tools, and the choice between them depends on your specific needs and coding preferences. isort is specialized in import sorting, while autopep8 covers a broader range of code formatting aspects.

Video Explanation 

In order to explain this topic in more detail, we have prepared a special video for you. Enjoy watching it!

Advanced Configuration Options for isort

While isort provides a seamless way to automatically sort and format your Python imports, it also offers advanced configuration options to tailor its behavior to your specific project needs. Let’s delve into some of these advanced settings:

  1. Config Files: You can create a configuration file (e.g., .isort.cfg or pyproject.toml) to define sorting preferences, import sections, and exclusion rules. This allows you to maintain consistent import styles across your project;
  2. Custom Sections: isort allows you to create custom import sections, which can be helpful for categorizing and organizing imports based on your project’s structure. For example, you can have separate sections for third-party libraries, standard library modules, and local imports;
  3. Line Length: You can set a maximum line length for your imports, ensuring that they remain within the specified character limit. This is particularly useful for projects with strict coding standards;
  4. Skip Files and Lines: Exclude specific files or lines within files from the import sorting process. This is handy when you have imports that should not be modified or when dealing with autogenerated code;
  5. Import Reordering: Customize the order in which imports are sorted, such as placing local imports before third-party imports or sorting by module length;
  6. Implicit Namespaces: Specify whether you want to use implicit namespaces (e.g., import numpy as np) or expand them to explicit imports (e.g., import numpy as numpy). This gives you control over how you import modules;
  7. Multi-Line Imports: Determine whether multi-line imports should be sorted as a single block or individually;
  8. Known Third-Party Libraries: Define a list of third-party libraries that should be treated as standard library modules, preventing unnecessary reordering;
  9. Force Single-Line Imports: Configure isort to force all imports onto a single line, which can be useful for adhering to specific coding standards;
  10. Alphabetical Sorting: Customize the order in which imports are sorted alphabetically, allowing you to prioritize specific modules or groups.

By harnessing these advanced configuration options, you can fine-tune isort to match your project’s import sorting requirements precisely. Whether you’re working on a small script or a large codebase, isort’s flexibility empowers you to maintain clean and organized import statements effortlessly.

Conclusion 

In this article, we’ve explored how to use Isort to automatically organize and sort module imports in Python files. This tool helps maintain a clean and consistent structure across your project, making it easier to collaborate with others and ensure code quality.

Feel free to leave comments if you have questions or suggestions. For more Python programming tutorials, check out our other articles.

FAQ

1. What is Python isort, and why should I use it?

isort is a Python utility and library designed to automatically sort and format import statements in your Python code. You should use it to ensure that your import statements are organized consistently and follow a standardized style. This is particularly beneficial as your projects grow and involve multiple developers with varying preferences for import ordering.

2. Can I customize the order in which imports are sorted?

Absolutely. isort provides advanced configuration options, allowing you to customize import sorting behavior. You can define custom sections, set line length limits, reorder imports based on your preferences, and more.

3. What if I have imports that should not be sorted or modified?

isort allows you to skip specific files or lines within files from the import sorting process. This feature is useful when dealing with autogenerated code or specific import statements that should remain untouched.

4. Does isort support Python 3 and Python 2?

Yes, isort supports both Python 3 and Python 2, making it a versatile tool for various Python projects.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published.

Programming on a laptop Previous post Mastering Spell Checking in Python
Close up of coding program on screen Next post Exploring Python’s Lambda Functions for Multiple Parameters