3

I import urlparse instead of urllib.parse in python 2.7 but getting AttributeError: 'function' object has no attribute 'unquote'

File "./URLDefenseDecode2.py", line 40, in decodev2
    htmlencodedurl = urlparse.unquote(urlencodedurl)

What is the equivalent urllib.parse.unquote() in python 2.7 ?

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
irom
  • 3,316
  • 14
  • 54
  • 86

2 Answers2

5

In Python 2.7, unquote is directly in urllib: urllib.unquote(string)

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • 1
    Unfortunately it does not behave exactly the same as the version in Python 3, especially wrt. encoding. – mbarkhau Sep 02 '20 at 10:42
3

The semantics of Python 3 urllib.parse.unquote are not the same as Python 2 urllib.unqote, especially when dealing with non-ascii strings.

The following code should allow you to always use the newer semantics of Python 3 and eventually you can just remove it, when you no longer need to support Python 2.

try:
    from urllib.parse import unquote
except ImportError:
    from urllib import unquote as stdlib_unquote

    # polyfill. This behaves the same as urllib.parse.unquote on Python 3
    def unquote(string, encoding='utf-8', errors='replace'):
        if isinstance(string, bytes):
            raise TypeError("a bytes-like object is required, not '{}'".format(type(string)))

        return stdlib_unquote(string.encode(encoding)).decode(encoding, errors=errors)
mbarkhau
  • 8,190
  • 4
  • 30
  • 34