Python: Importing urllib.quote

PythonPython 3.xImportUrllib

Python Problem Overview


I would like to use urllib.quote(). But python (python3) is not finding the module. Suppose, I have this line of code:

print(urllib.quote("châteu", safe=''))

How do I import urllib.quote?

import urllib or import urllib.quote both give

AttributeError: 'module' object has no attribute 'quote'

What confuses me is that urllib.request is accessible via import urllib.request

Python Solutions


Solution 1 - Python

In Python 3.x, you need to import urllib.parse.quote:

>>> import urllib.parse
>>> urllib.parse.quote("châteu", safe='')
'ch%C3%A2teu'

According to Python 2.x urllib module documentation:

> NOTE > > The urllib module has been split into parts and renamed in Python 3 to > urllib.request, urllib.parse, and urllib.error.

Solution 2 - Python

If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

You could also use the python compatibility wrapper six to handle this.

from six.moves.urllib.parse import quote

Solution 3 - Python

urllib went through some changes in Python3 and can now be imported from the parse submodule

>>> from urllib.parse import quote  
>>> quote('"')                      
'%22'                               

Solution 4 - Python

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

Solution 5 - Python

Use six:

from six.moves.urllib.parse import quote

six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionimrekView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythoneanderssonView Answer on Stackoverflow
Solution 3 - PythonJustin FayView Answer on Stackoverflow
Solution 4 - PythonYutenjiView Answer on Stackoverflow
Solution 5 - PythonJamesThomasMoonView Answer on Stackoverflow