Flake8 plugin that checks import order against various Python Style Guides

Overview

flake8-import-order

Build Status

A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely that they are grouped and ordered correctly.

In general stdlib comes first, then 3rd party, then local packages, and that each group is individually alphabetized, however this depends on the style used. Flake8-Import-Order supports a number of styles and is extensible allowing for custom styles.

This plugin was originally developed to match the style preferences of the cryptography project, with this style remaining the default.

Warnings

This package adds 4 new flake8 warnings

  • I100: Your import statements are in the wrong order.
  • I101: The names in your from import are in the wrong order.
  • I201: Missing newline between import groups.
  • I202: Additional newline in a group of imports.

Styles

The following styles are directly supported,

  • cryptography - see an example
  • google - style described in Google Style Guidelines, see an example
  • smarkets - style as google only with import statements before from X import ... statements, see an example
  • appnexus - style as google only with import statements for packages local to your company or organisation coming after import statements for third-party packages, see an example
  • edited - see an example
  • pycharm - style as smarkets only with case sensitive sorting imported names
  • pep8 - style that only enforces groups without enforcing the order within the groups

You can also add your own style by extending Style class.

Configuration

You will want to set the application-import-names option to a comma separated list of names that should be considered local to your application. These will be used to help categorise your import statements into the correct groups. Note that relative imports are always considered local.

You will want to set the application-package-names option to a comma separated list of names that should be considered local to your company or organisation, but which are obtained using some sort of package manager like Pip, Apt, or Yum. Typically, code representing the values listed in this option is located in a different repository than the code being developed. This option is only accepted in the supported appnexus or edited styles or in any style that accepts application package names.

The application-import-names and application-package-names can contain namespaced packages or even exact nested module names. (This is possible with 0.16 onwards).

import-order-style controls what style the plugin follows (cryptography is the default).

Limitations

Currently these checks are limited to module scope imports only. Conditional imports in module scope will also be ignored.

Classification of an imported module is achieved by checking the module against a stdlib list and then if there is no match against the application-import-names list and application-package-names if the style accepts application-package names. Only if none of these lists contain the imported module will it be classified as third party.

These checks only consider an import against its previous import, rather than considering all the imports together. This means that I100 errors are only raised for the latter of adjacent imports out of order. For example,

import X.B
import X  # I100
import X.A

only import X raises an I100 error, yet import X.A is also out of order compared with the import X.B.

Imported modules are classified as stdlib if the module is in a vendored list of stdlib modules. This list is based on the latest release of Python and hence the results can be misleading. This list is also the same for all Python versions because otherwise it would be impossible to write programs that work under both Python 2 and 3 and pass the import order check.

The I202 check will consider any blank line between imports to count, even if the line is not contextually related to the imports. For example,

import logging
try:
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        """Shim for version of Python < 2.7."""

        def emit(self, record):
            pass
import sys  # I202 due to the blank line before the 'def emit'

will trigger a I202 error despite the blank line not being contextually related.

Extending styles

You can add your own style by extending flake8_import_order.styles.Style class. Here's an example:

from flake8_import_order.styles import Cryptography


class ReversedCryptography(Cryptography):
    # Note that Cryptography is a subclass of Style.

    @staticmethod
    def sorted_names(names):
        return reversed(Cryptography.sorted_names(names))

By default there are five import groupings or sections; future, stdlib, third party, application, and relative imports. A style can choose to accept another grouping, application-package, by setting the Style class variable accepts_application_package_names to True, e.g.

class PackageNameCryptography(Cryptography):
    accepts_application_package_names = True

To make flake8-import-order able to discover your extended style, you need to register it as flake8_import_order.styles using setuptools' entry points mechanism:

# setup.py of your style package
setup(
    name='flake8-import-order-reversed-cryptography',
    ...,
    entry_points={
        'flake8_import_order.styles': [
            'reversed = reversedcryptography:ReversedCryptography',
            # 'reversed' is a style name.  You can pass it to
            # --import-order-style option
            # 'reversedcryptography:ReversedCryptography' is an import path
            # of your extended style class.
        ]
    }
)
Owner
Python Code Quality Authority
Organization for code quality tools (and plugins) for the Python programming language
Python Code Quality Authority
Type stubs for the lxml package

lxml-stubs About This repository contains external type annotations (see PEP 484) for the lxml package. Installation To use these stubs with mypy, you

25 Dec 26, 2022
An enhanced version of the Python typing library.

typingplus An enhanced version of the Python typing library that always uses the latest version of typing available, regardless of which version of Py

Contains 6 Mar 26, 2021
A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

flake8-bugbear A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycode

Python Code Quality Authority 869 Dec 30, 2022
Plugin for mypy to support zope.interface

Plugin for mypy to support zope.interface The goal is to be able to make zope interfaces to be treated as types in mypy sense. Usage Install both mypy

Shoobx 36 Oct 29, 2022
Convert relative imports to absolute

absolufy-imports A tool and pre-commit hook to automatically convert relative imports to absolute. Installation $ pip install absolufy-imports Usage a

Marco Gorelli 130 Dec 30, 2022
The mypy playground. Try mypy with your web browser.

mypy-playground The mypy playground provides Web UI to run mypy in the sandbox: Features Web UI and sandbox for running mypy eas

Yusuke Miyazaki 57 Jan 02, 2023
Reference implementation of sentinels for the Python stdlib

Sentinels This is a reference implementation of a utility for the definition of sentinel values in Python. This also includes a draft PEP for the incl

Tal Einat 22 Aug 27, 2022
Pylint plugin to enforce some secure coding standards for Python.

Pylint Secure Coding Standard Plugin pylint plugin that enforces some secure coding standards. Installation pip install pylint-secure-coding-standard

Nguyen Damien 2 Jan 04, 2022
Flake8 plugin for managing type-checking imports & forward references

flake8-type-checking Lets you know which imports to put in type-checking blocks. For the imports you've already defined inside type-checking blocks, i

snok 67 Dec 16, 2022
Python classes with types validation at runtime.

typedclasses Python classes with types validation at runtime. (Experimental & Under Development) Installation You can install this library using Pytho

Izhar Ahmad 8 Feb 06, 2022
A simple program which checks Python source files for errors

Pyflakes A simple program which checks Python source files for errors. Pyflakes analyzes programs and detects various errors. It works by parsing the

Python Code Quality Authority 1.2k Dec 30, 2022
Flake8 extension for enforcing trailing commas in python

Flake8 Extension to enforce better comma placement. Usage If you are using flake8 it's as easy as: pip install flake8-commas Now you can avoid those a

Python Code Quality Authority 127 Sep 03, 2022
Tools for improving Python imports

imptools Tools for improving Python imports. Installation pip3 install imptools Overview Detailed docs import_path Import a module from any path on th

Danijar Hafner 7 Aug 07, 2022
Tool to automatically fix some issues reported by flake8 (forked from autoflake).

autoflake8 Introduction autoflake8 removes unused imports and unused variables from Python code. It makes use of pyflakes to do this. autoflake8 also

francisco souza 27 Sep 08, 2022
Easy saving and switching between multiple KDE configurations.

Konfsave Konfsave is a config manager. That is, it allows you to save, back up, and easily switch between different (per-user) system configurations.

42 Sep 25, 2022
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 2.6k Jan 03, 2023
Flake8 Type Annotation Checking

flake8-annotations flake8-annotations is a plugin for Flake8 that detects the absence of PEP 3107-style function annotations and PEP 484-style type co

S. Co1 118 Jan 05, 2023
Static type checker for Python

Static type checker for Python Speed Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fas

Microsoft 9.2k Jan 03, 2023
🦆 Better duck-typing with mypy-compatible extensions to Protocol

🦆 Quacks If it walks like a duck and it quacks like a duck, then it must be a duck Thanks to PEP544, Python now has protocols: a way to define duck t

Arie Bovenberg 9 Nov 14, 2022
❄️ A flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Adam Johnson 398 Dec 23, 2022