2to3 makes multiple imports
Asked Answered
T

1

6

I'm writing python2 code that will be be portable for python3 as well (by running 2to3 during user installation).

But 2to3 sometimes makes multiple imports:

-import urlparse
-import urllib
-import urllib2
+import urllib.parse
+import urllib.request, urllib.parse, urllib.error
+import urllib.request, urllib.error, urllib.parse

How can I make 2to3 aware of duplicates?

Twink answered 1/2, 2014 at 13:42 Comment(3)
Do you have to? As far as I know, importing standard library modules is free of side-effects, so there's no harm in importing them multiple times.Membranophone
@Membranophone Well, I can get away with it, but I thought there might be a better wayTwink
This obviously doesn't answer your question directly but you could try passing the results of 2to3 through the isort module.Wheelbarrow
A
0

This might be the reason http://www.diveinto.org/python3/porting-code-to-python-3-with-2to3.html

Specifically, the urllib library changes between python 2 and python 3. Here are the specific changes

Python 2                                Python 3
import urllib                           import urllib.request, urllib.parse, urllib.error
import urllib2                          import urllib.request, urllib.error
import urlparse                         import urllib.parse
import robotparser                      import urllib.robotparser   
from urllib import FancyURLopener       from urllib.request import FancyURLopener
from urllib import urlencode            from urllib.parse import urlencode
from urllib2 import Request             from urllib.request import Request
from urllib2 import HTTPError           from urllib.error import HTTPError 

As far as I can tell there is no way to avoid this without parsing of some kind - if you want to pursue that method then isort (as suggested in the comments to your question) is likely your best bet. Alternatively you could parse the code on your own, or just accept that you can't easily fix this issue and it is unlikely to cause any real problems in your code.

Assyria answered 14/2, 2014 at 18:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.