flake8: import statements are in the wrong order
Asked Answered
T

1

9

PEP8 suggests that:

Imports should be grouped in the following order:

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

You should put a blank line between each group of imports.

I am using Flake8Lint which Sublime Text plugin for lint Python files.

My code as below:

import logging
import re
import time
import urllib
import urlparse

from flask import Blueprint
from flask import redirect
from flask import request
from flask.ext.login import current_user
from flask.ext.login import login_required

from my_application import one_module

it will show the warning as below:

import statements are in the wrong order, from my_application should be before from from flask.ext.login

but flask is the third party library, it should before my my_application import. This is why? How to fix it?

Teliospore answered 28/9, 2016 at 6:1 Comment(3)
I suppose it's because of „library specific imports” - probably Flake8Link understand that flask.ext.login is specific for library. I'd say - ignore flake8 error.Waddington
According to Flake8Lint the import order checks are off unless you specify them. Further, it's using flake8-import-order which let's you tell it what your application name is so it knows what is a local import.Calyx
At the end of the day, it really doesn't matter. As long as your imports are grouped in a reasonable manner to you and the people that will be reading your code after you, don't worry about whether an automated checker thinks module a should be imported before or after module b.Monopolist
S
12

The flake8-import-order plugin needs to be configured to know which names should be considered local to your application.

For your example, if using a .flake8 ini file in your package root directory, it should contain:

[flake8]
application_import_names = my_application

Alternatively you can use only relative imports for application local imports:

from __future__ import absolute_import

import os
import sys

import requests

from . import (
    client
)


...
Sikh answered 28/9, 2017 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.