6

First of all, yes I'm aware of PEP8 and the alphabetical method.

I do sort my imports first by the PEP8 recommendation:

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

But then, within each category, I like to sort by the length of the module name. Yes, it makes it look pretty, but then I find it arguably makes it easier to find a module than the alphabetical way.

Also, the shorter names tend to be the more basic, common modules (like os and sys), so there's an additional organization layer in that way. You know the length of the name you're looking for, and the visual shape of the import list tells you very quickly where to look for names that long.

An example:

import os
import sys
import time
import logging
import argparse
import subprocess

import django
import requests
import webencodings

import mymodule
import localthing
import supercustomstuff

Right now I mostly write for myself, and I don't work with a team. But I intend to in the future. So what I'm wondering is, does anyone else do this, does anyone else see the sense in it, or will everyone else think I'm nuts?

Edit: Separate subgroups in example, as suggested by Mark Ransom, in order not to distract from the core issue about the ordering.

9
  • 1
    How do you decide what to put first when 2 modules have the same name length and belong in the same category? I would certainly say that for your own stuff, if it helps you, do it. I would not want someone doing that on a project I work on, though. Commented Feb 14, 2018 at 3:04
  • @user1118321 Usually I put the more "basic" ones above the rarer or more specialized ones. Good to hear the feedback. I'd love to hear you expand on why in an answer.
    – Nick S
    Commented Feb 14, 2018 at 3:13
  • 2
    Sounds to me like another firm of technical procrastination Commented Feb 14, 2018 at 3:52
  • 1
    The obvious downside of using an unusual style is that tools cannot help you maintain that style. There are tools that sort Python imports alphabetically. Do you know of any tools that automatically create your preferred order? Commented Feb 14, 2018 at 10:45
  • 1
    Just to quickly answer one more of your questions, you're not the only one, this is also my usual approach. Even though I don't have any reasoning behind this approach other than "it's aesthetically appealing". Commented Feb 18, 2018 at 16:25

7 Answers 7

5

First, I would say to do what works for you on your own projects. It’s not going to hurt anything and it helps you, so it’s a win!

For projects with others I would discuss it with the team. Often a team will have a style guide that they expect developers to follow. Other times they allow every developer to do their own thing. I would advise following what others on your team do.

Personally, your system seems arbitrary to me and quite odd. Others probably have systems they use for equally arbitrary reasons. I don’t feel like yours would help me in general. I have to wonder how much it helps when the module names are all close in length? At least with alphabetic (which is also not my favorite) I know to use the first 2 letters when two files start with the same letter.

Also, I’m not sure about Python but in some languages, if developers aren’t careful, import order can change the behavior of a program. (That shouldn’t be the case and it shouldn’t be relied on, but the reality is that it happens.)

6

This is a classic XY question. You ask about one issue, but I will suggest you actually have a different issue!

You say sorting by length makes it easier to find a module. So apparently you spend a significant amount of effort scanning through the list of imports to see if a certain import is present. This indicates to me you have far to many imports in a single file. Each file have too many different responsibilities and dependencies. Apply some modularization and separation of concerns to your own code, so each file will have a manageable number of dependencies. You should be able to see all imports in a section at a glance so ordering shouldn't matter that much.

As for sorting by name length, this does not make a lot of sense. The length of a name does not carry any particular meaning. Module names are selected to be simple and descriptive, but the length does not necessarily correspond to how "basic" they are, even if it happens to be the case in the examples you chose.

If you want to sort by how basic the modules are (which is reasonable) then do that, and ignore the length of names.

2
  • 1
    Though the example given by the OP do not appear to me as being too much... your reasonning is spot-on ! Identifying the problem is one thing but it's only the first step towards understanding it.
    – Newtopian
    Commented Feb 15, 2018 at 19:07
  • 1
    Well this is a pretty interesting thought. I'm not sure what's too many, but I'd say about a dozen is typical for my scripts. I don't think I spend much time scanning; the comment about ease of scanning is mainly a preemptive response to those arguing for alphabetical. And the "basic"ness isn't the main motivation, but mainly a nice side effect. In any case, if you have advice on modularization to point to, I'd love to read it.
    – Nick S
    Commented Feb 16, 2018 at 7:09
3

Your ordering is weird. If you intend to work with other people, don't do it. Even if you're working on your own private project, don't allow yourself to get into bad habits.

I'd also put a blank line between the groups to separate them.

2
  • By ‘weird’ do you mean uncommon practice, unfamiliar to you, can’t understand the benefit or something else? Commented Mar 13, 2021 at 11:31
  • 1
    @JBRWilkinson by "weird" I mean something that you're unlikely to find anybody else doing. It would never have occurred to me to order my imports that way. If I found myself in a group that had settled on that convention, I'd have a hard time getting used to it. Commented Mar 13, 2021 at 15:59
1

It's indeed you own style and I see no harm in keeping it.

But, I'd say its rooted in a deeper instinct of a "natural order", or in fact a combination of various such orders:

  1. Common imports that are almost in every file always go in first. This is not surprising as the imports section slowly becomes a template in your head. A quick glance and you know what's "special" imported here.

  2. More specific things usually tend to have longer names, namespaces and import paths. So, the "generic first and specialized later" rule actually ends up with the length based ordering.

  3. The urge to group, categorize and separately mark everything is also pretty common. Closely related imports are usually grouped together.

  4. And finally, we cannot ignore the "visual aesthetics" of text, many programmers regard highly. We are arranging the information for our own quick processing.

1

I'll just add my two cents as someone who's been sorting by line length for a couple of years now.

The way I see it, the two biggest advantages of this sort are

  1. Reduced cognitive load - it's natural for us to sort by length, no need to recite the alphabet in your head every time you make a change. And unlike alphabetical sorting, when things are not sorted by length, they immediately stand out, which makes it better to maintain.

  2. Visuals - it is subjective, but I think the second one looks much better:

  • Alphabetical + grouping:
import time
import logging
import multiprocessing as mp
import os
import time

from package1 import module1
import package1.module2
from package1.module3 import cfg

from package2 import class1
from package2.subpackage1.module5 import functionC
from package2.subpackage3 import functionB
  • Length + grouping
import os
import time
import logging
import argparse
import multiprocessing as mp

import package1.module2
from package1 import module1
from package1.module3 import cfg

from package2 import class1
from package2.subpackage3 import functionB
from package2.subpackage1.module5 import functionC

As for some other comments saying it's "weird" or that "it does not make a lot of sense".

Neither does alphabetical sorting. It's a mere consensus that is totally arbitrary. There's no deeper meaning or great advantage to either one. Alphabetical sorting makes it slightly easier to find packages when they have similar lengths, but aren't you using Ctrl+F or '?' commands to search longer import lists anyway? Personally, the two advantages above far outweigh a paltry improvement in lookup time.

2
  • 1
    I have to say, I've since made myself switch to alphabetical, and I do notice the additional effort when I'm placing a new import. Maybe we're just the minority who take more thinking to alphabetize! But after trying both, I can say that length-ordering is easier for me.
    – Nick S
    Commented Mar 12, 2021 at 16:46
  • 1
    nice - the funny thing is that I don't find alphabetical sorting hard at all, but sorting by length is even easier and it looks better, so why not? Commented Mar 12, 2021 at 16:51
0

First, I'll echo @user1118321 that this rule is fine if it works for you and that in a team, just come to an agreement to avoid personal and source merge conflicts.

How does your rule handle imports that say more than import abcd? Imports frequently look like these:

from typing import Dict, Iterator, List, Set
from google.cloud.storage import Blob, Client
import numpy as np
from . import mymodule

If the module-name-length rule discourages using these import features, or make you reorder the lines when adding more types to an import line, or defeat the visual order that was the point, then the rule is probably doing more harm than good.

Personally I'd rather let PyCharm "optimize imports", and that'd also avoid some source merge conflicts, but teammates are not careful about import order, I don't want my editor to accidentally reorder their imports, and there's no reason to disagree over it.

0

Looking at your first group of imports for example, I can’t see any real reason for any ordering. Therefore, I don’t really care how you order it. Your business. It would never occur to me why the imports are ordered the way they are, so I’d add a new import at the end of the list, and you could feel free to move it elsewhere.

I find it useful to know why some import is needed, as a comment, unless it is obvious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.