1

We have a lot of files with ugly import statements like this:

from project.foo import a, b
from project.foo import c
from project.bar import d, e, f, g

Does there exist something that will change them all to one import per line?

from project.foo import a
from project.foo import b
from project.foo import c
from project.bar import d
from project.bar import e
from project.bar import f
from project.bar import g

Clarification: The reason for this is to maintain a consistent style, like Google's style guide for Python.

5
  • 3
    why would you want one import per line? Commented Oct 7, 2011 at 20:24
  • 4
    Don't bring java habits to Python Commented Oct 7, 2011 at 20:40
  • I agree with JBernardo. I do java at work and I hate this. Unnecessary junk. Commented Oct 7, 2011 at 20:41
  • I appreciate all the sentiment. You have convinced me! However, I'll leave this question in the case that someone really wants to do what I asked. Commented Oct 9, 2011 at 4:36
  • I would be more useful to have a utility that fixes from foo import * to from foo import a, b. Commented Aug 22, 2015 at 9:17

2 Answers 2

7

As per PEP8 style guide:

Imports

- Imports should usually be on separate lines, e.g.:

    Yes: import os
         import sys

    No:  import sys, os

  it's okay to say this though:

    from subprocess import Popen, PIPE

So, I think you should be doing what you are and should not split them. I am not aware of any utility which will do that for you.

Also, if:

project.bar contains say: d,e,f,g,x,y,z then I would say just do a import project.bar, code will be much less and easy for the eyes.

Sign up to request clarification or add additional context in comments.

1 Comment

As a note, I would recommend the OP to import project.bar with import project.bar as bar and use bar.d, bar.e etc.
0

sed can do that with something like this (test first as I don't have access to my Linux box to test it at the moment):

sed -i".backup" 's/from ([^ ]+) import ([^,]+), ([^,]+)/from \1 import \2\nfrom \1 import \3/' *.py

1 Comment

Hmm: sed: -e expression #1, char 76: invalid reference \3 on s' command's RHS`

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.