Utility to fix Python import style? - python

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.

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.

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

Related

How can i run import statements from a seperate .py file?

So I routinely call the same 15-20 import statements prior to running multiple, but different .py scripts. This can sort of look clunky and I was wondering if I could, for the sake of condensing, store all of these import statements in a separate .py file, then call those import statements using a 1 - liner at the beginning of these .py scripts.
e.g.:
import a
import b
import c
import d
import e
import f
(and so on so forth)
into:
import import_list import imports
I've tried search around but I'm not sure I'm using the correct language to get my answer. I'm sure this has been asked quite a few times though. can anybody help? thanks!
If your import list is constant, you could do something like creating a separate python file like
import_list.py
import a
import b
import c
import d
import e
import f
Then add 1 liner to your files:
from import_list import *

Pylint complains when importing in the right order

I thought the correct order of imports in Python was the one described by the first answer of the question: What's the correct way to sort Python `import x` and `from x import y` statements?
Therefore, this code should be correct:
import os
import time
import yaml
from collections import OrderedDict
from xtesting.core import testcase
However, when I run Pylint I get:
C: 5, 0: standard import "from collections import OrderedDict" should be placed before "import yaml" (wrong-import-order)
So I guess "yaml" is not a standard library. Should then the correct way to do it be this one (even if it is uglier and less readable)?
import os
import time
from collections import OrderedDict
import yaml
from xtesting.core import testcase
PyYAML is not part of the standard Python library and imports from the standard library, whether generic (import os) or specific (from collections import OrderedDict) should come first.
You should, IMO, lexicographically sort on the module names in the sections and separate the sections with an empty line:
from collections import OrderedDict
import os
import time
from xtesting.core import testcase
import yaml
There are some that want the generic ones to all come first, in each section:
import os
import time
from collections import OrderedDict
import yaml
from xtesting.core import testcase
This looks nicer, but it makes it easier to overlook specific imports after a long generic lists. And it also separates a generic and specific import from one and the same module, which, IMO, is bad:
import yaml
from xtesting.core import testcase
from yaml import safe_load

how to import module only once in python behave step files

I am very new to Python and Behave. In my step file, test_steps.py, I have imported the following:
from behave import given, when, then, step
from behave_http.steps import *
from datetime import datetime
import time
import pdb
import xmltodict
import requests
If I created another step file, test2_steps.py, I had to import above again.
Is there a way to avoid that?
Thank you for your help!
It's generally useful to know all the imports for a given file; however, you can do something like the following:
config.py
from behave import given, when, then, step
from behave_http.steps import *
from datetime import datetime
import time
import pdb
import xmltodict
import requests
test2_steps.py
from config import *
#other code here

How can I use import, from import and sys.append together in Python

I have a directory I add to sys.path to import custom modules. What is the correct/best way to use import, from import and sys.path together? What I mean is if it acceptable to use sys.path.append in between the "imports".
For example:
#!C:/Python27
import sys
sys.path.append('C:\\Users\\user\\myPythonModules')
import writedata as wd
import os
import csv
from collections import defaultdict
Edit:
I should have mentioned that writedata would be a custom module that I want to import as wd. The module writedata is located in C:\\Users\\user\\myPythonModules
Yes, it is. There is no syntax or semantic rule in the language that prevents that.
I am not aware of any "style" rule that you may be breaking, but in any case, another option is providing PYTHONPATH to the python interpreter.

Python Module Import: Single-line vs Multi-line

When importing modules in Python, what is the difference between this:
from module import a, b, c, d
and this
from module import a
from module import b
from module import c
from module import d
To me it makes sense always to condense code and use the first example, but I've been seeing some code samples out there dong the second. Is there any difference at all or is it all in the preference of the programmer?
There is no difference at all. They both function exactly the same.
However, from a stylistic perspective, one might be more preferable than the other. And on that note, the PEP-8 for imports says that you should compress from module import name1, name2 onto a single line and leave import module1 on multiple lines:
Yes: import os
import sys
No: import sys, os
Ok: from subprocess import Popen, PIPE
In response to #teewuane's comment (repeated here in case the comment gets deleted):
#inspectorG4dget What if you have to import several functions from one
module and it ends up making that line longer than 80 char? I know
that the 80 char thing is "when it makes the code more readable" but I
am still wondering if there is a more tidy way to do this. And I don't
want to do from foo import * even though I am basically importing
everything.
The issue here is that doing something like the following could exceed the 80 char limit:
from module import func1, func2, func3, func4, func5
To this, I have two responses (I don't see PEP8 being overly clear about this):
Break it up into two imports:
from module import func1, func2, func3
from module import func4, func5
Doing this has the disadvantage that if module is removed from the codebase or otherwise refactored, then both import lines will need to be deleted. This could prove to be painful
Split the line:
To mitigate the above concern, it may be wiser to do
from module import func1, func2, func3, \
func4, func5
This would result in an error if the second line is not deleted along with the first, while still maintaining the singular import statement
To add to some of the questions raised from inspectorG4dget's answer, you can also use tuples to do multi-line imports when folder structures start getting deeply nested or you have modules with obtuse names.
from some.module.submodule.that_has_long_names import (
first_item,
second_item,
more_imported_items_with_really_enormously_long_names_that_might_be_too_descriptive,
that_would_certainly_not_fit,
on_one_line,
)
This also works, though I'm not a fan of this style:
from module import (a_ton, of, modules, that_seem, to_keep, needing,
to_be, added, to_the_list, of_required_items)
I would suggest not to follow PEP-8 blindly. When you have about half screen worth of imports, things start becoming uncomfortable and PEP-8 is then in conflicts with PEP-20 readability guidelines.
My preference is,
Put all built-in imports on one line such as sys, os, time etc.
For other imports, use one line per package (not module)
Above gives you good balance because the reader can still quickly glance the dependencies while achieving reasonable compactness.
For example,
My Preference
# one line per package
import os, json, time, sys, math
import numpy as np
import torch, torch.nn as nn, torch.autograd, torch.nn.functional as F
from torchvision models, transforms
PEP-8 Recommandation
# one line per module or from ... import statement
import os
import json
import time
import sys
import math
import numpy as np
import torch
from torch import nn as nn, autograd, nn.functional as F
from torchvision import models, transforms
A concern not mentioned by other answers is git merge conflicts.
Let's say you start with this import statement:
import os
If you change this line to import os, sys in one branch and import json, os in another branch, you will get this conflict when you attempt to merge them:
<<<<<<< HEAD
import os, sys
=======
import json, os
>>>>>>> branch
But if you add import sys and import json on separate lines, you get a nice merge commit with no conflicts:
--- a/foo.py
+++ b/foo.py
### -1,2 -1,2 +1,3 ###
+ import json
import os
+import sys
You will still get a conflict if the two imports were added at the same location, as git doesn't know which order they should appear in. So if you had imported time instead of json, for example:
import os
<<<<<<< HEAD
import sys
=======
import time
>>>>>>> branch
Still, it can be worth sticking with this style for the occasions where it does avoid merge conflicts.
Imports should usually be on separate lines as per PEP 8 guidelines.
# Wrong Use
import os, sys
# Correct Use
import os
import sys
For more import based PEP 8 violations and fixes please check this out https://ayush-raj-blogs.hashnode.dev/making-clean-pr-for-open-source-contributors-pep-8-style.
Both are same.
Use from module import a, b, c, d.
If you want to import only one part of a module, use:
from module import a
If u want to import multiple codes from same module, use:
from module import a,b,c,d
No need to write all in separate lines when both are same.

Categories

Resources