Lewis20
Lewis20

Reputation: 19

Converting Python 3 libraries to be used in 2.7

I'm following a tutorial which is coded in Python 3 and the author uses

from urllib import parse

which gives me an error.

I've tried using Google and reading up about the library but can't seem to find equivalent. All my code for project is in 2.7 so I would prefer not to have to move over 3 just for this little bit.

Thanks for any help in advance.

Upvotes: 0

Views: 136

Answers (2)

user707650
user707650

Reputation:

Make your code Python 2 compatible without losing Python 3 compatibility. You could use a library like six, but for just this single import, this may suffice:

try:
    from urllib import parse
except ImportError:
    import urlparse as parse

Note that you may have "invisible" compatibility issues though. For example, standard division in Python 3 is always floating pointing division, even between two integers, while in Pyhton 2 this is not. Thus, while not likely with code that deals with URL parsing, you may want to add

from __future__ import division

at the top of the Python 3 code as well.


Generally, I recommend writing and using Python 3 code, making it Python 2 compatible where needed, but not converting it to Python 2 (i.e., not using the 3to2 or 2to3 tools, but use e.g. six or some try-except imports).

This way, that code is already Py3 ready, but still works with Py2.

Upvotes: 1

Jesse Bakker
Jesse Bakker

Reputation: 2623

Urllib has been restructured in python 3. What was urlparse in python 2, is now urllib.parse (in python 3). So just use urlparse. You can even do this: import urlparse as parse and the rest of the code should be the same.

Upvotes: 1

Related Questions