11

In my python script - youdao.py, in order to be compatible with python2 and python3, I import urlopen like this style:

try:
    # compatible for python2
    from urllib import urlencode
    from urllib2 import urlopen
except ImportError:
    # compatible for python3
    from urllib.parse import urlencode
    from urllib.request import urlopen

See details in https://github.com/MintCN/youdao-python/blob/master/youdao_simple/youdao.py#L22

When you use pylint youdao.py, you will see ungrouped-imports warning, how do I modify code to remove this warning?

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
慕冬亮
  • 339
  • 1
  • 2
  • 10

2 Answers2

28

I had similar issue. Pylint prefers grouping of packages.

CASE 1: Causes ungrouped-imports warning

import keras
import sklearn

from keras import losses
from sklearn import svm

CASE 2: [No Warning]

import keras
from keras import losses

import sklearn
from sklearn import svm
Nikhil
  • 1,054
  • 9
  • 9
  • 1
    Please have a look at my python code. There is not single "import" statement. You mean I need to add two "import" statements before "from ... import ...", right? – 慕冬亮 Feb 26 '18 at 21:05
  • Then it will give unused import, instead what python expects is reordering them together. In this case `from urllib2 import urlopen` can be written above `urlib import` – Akshay Hazari Nov 26 '20 at 02:22
  • This is unbelievably incredible :) – Maf Dec 03 '20 at 02:14
5
try:
    # compatible for python2
    # from urllib import urlencode
    from urllib2 import urlopen
    from urllib import urlencode
except ImportError:
    # compatible for python3
    from urllib.parse import urlencode
    from urllib.request import urlopen

This fixes it -- all urllib imports should appear uninterrupted; otherwise pylint complains.

mikey
  • 2,158
  • 1
  • 19
  • 24
  • 1
    Did you write anything different than OP – Akshay Hazari Nov 26 '20 at 02:17
  • As a matter of fact, there is a "2" in `from urllib2 import urlopen` instead of `from urllib import urlencode`. Admittedly it took myself a while to locate it. The question and hence my answer is probably moot since not too many people still use Python2? – mikey Nov 26 '20 at 04:16
  • Understood, we need grouping of urllib together. Then it resolves. So all similar package imports come together, like reordering them together. You can add may be another line to clarify. Uninterrupted had me quizzed. – Akshay Hazari Nov 26 '20 at 05:37