Auto-import doesn't follow PEP8
Asked Answered
H

1

16

Consider the following code:

from bs4 import BeautifulSoup


data = "<test>test text</test>"
soup = BeautifulSoup(data)
print(soup.find(text=re.compile(r'test$')))

It is missing an import re line and would fail with a NameError without it.

Now, I'm trying to use PyCharm's Auto-Import feature: focusing on re and hitting Alt+Enter, which opens up the following popup:

enter image description here

Now, if I choose Import 're' option, Pycharm would insert the new import line at the top of the script:

import re
from bs4 import BeautifulSoup


data = "<test>test text</test>"
soup = BeautifulSoup(data)
print(soup.find(text=re.compile(r'test$')))

Looks almost good, except that it doesn't follow PEP8 import guidelines:

Imports should be grouped in the following order:

  • standard library imports

  • related third party imports

  • local application/library specific imports

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

In other words, there is a missing blank line between the two imports:

import re

from bs4 import BeautifulSoup

Question is: is it possible to tell Pycharm to follow the PEP8 guidelines and insert a new-line between the lines with different import types on auto-import?


As a workaround, I'm calling Optimize Imports after that organizes the imports correctly.

Hecht answered 8/12, 2014 at 23:51 Comment(3)
PyCharm claims to follow PEP8 with auto-imports, so you should probably file a bug report.Fulford
This is further complicated by ambiguity of distinction between standard, related and local imports. PyCharm could be smarter, sure, but in general case you cannot authoritatively state which group given import foo belongs to.Predict
@qarma that's a good point. Though, pycharm does a good job in organizing imports through Optimize imports in this case. This is something about auto-import here. Thanks.Hecht
H
9

You can't. Reason is PyCharm doesn't tell you that you have violated any PEP8 Guidelines if you do that or any import statements at all. One, your PyCharm is outdated (newest version is 4.0.2/4.2) or second, your PyCharm seems to be having a bug, thus giving reason to file a bug report. If you can try to safely download PyCharm again to try to fix the bug. If that doesn't work, file a bug report or make a habit of making a blank line between your statements. Hope this answers your question! Oh, it does not matter whether you use from, import, or both type of statements.

Helsinki answered 14/12, 2014 at 0:31 Comment(1)
Thank you, filed an issue at Pycharm's Issue Tracker.Hecht

© 2022 - 2024 — McMap. All rights reserved.