Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping import statements in python

Tags:

python

pylint

I have started learning python recently and ran pylint on my python file. I got following comments.

from os import listdir
from os.path import isfile, join

I the above two lines, the Pylinter comment is

C:  5, 0: Imports from package os are not grouped (ungrouped-imports)

How can I achieve that ?

And another comment is in below line

import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests

C:  5, 0: standard import "import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests" should be placed before "import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests" (wrong-import-order)

what does the above line mean and why is it required?

like image 358
ankit Avatar asked Aug 05 '18 17:08

ankit


People also ask

How do you organize import statements?

Automatically organise import statements whenever you saveGo to Window > Preferences > Java > Editor > Save Actions. Select Perform the selected actions on save (off by default). Ensure that Organize imports is selected (on by default).

What are the 3 types of import statements in Python?

There are generally three groups: standard library imports (Python's built-in modules) related third party imports (modules that are installed and do not belong to the current application) local application imports (modules that belong to the current application)

Does the order of imports matter in Python?

Import order does not matter. If a module relies on other modules, it needs to import them itself. Python treats each . py file as a self-contained unit as far as what's visible in that file.


1 Answers

PEP8 suggests to order and group imports like so:

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.

In your case, django and requests are third party imports, and so you should write

import mimetypes, time, csv, platform, base64, sys, os, math, uuid, linecache, logging

import django, requests

It can further be useful to alphabetize imports (in each group) when you have this many.

Further, pylint seems to like grouping beyond PEP8. In particular, imports from the same module/package should be grouped together. That is, add a space between your os imports and the rest, and maybe even throw the bare os import up there as well. In all:

import os
from os import listdir
from os.path import isfile, join

import base64, csv, linecache, logging, math, mimetypes, platform, time, sys, uuid

import django, requests 
like image 95
jmd_dk Avatar answered Sep 21 '22 11:09

jmd_dk