Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for Python 3's unquote making an alias of chr and int?

Tags:

python

urllib

In Python 3's function unquote (from http://www.opensource.apple.com/source/python/python-3/python/Lib/urllib.py):

def unquote(s):
    """unquote('abc%20def') -> 'abc def'."""
    mychr = chr
    myatoi = int
    list = s.split('%')
    res = [list[0]]
    myappend = res.append
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                myappend(mychr(myatoi(item[:2], 16))
                     + item[2:])
            except ValueError:
                myappend('%' + item)
        else:
            myappend('%' + item)
    return "".join(res)

We have the 2 first executed lines:

mychr = chr
myatoi = int

And their usage:

         ...
                myappend(mychr(myatoi(item[:2], 16))
                     + item[2:])
         ...

Why is there an alias of these 2 functions used, if they are only used in this function? They can easily be exchanged for chr and int.

like image 863
Ryan Avatar asked Dec 05 '25 05:12

Ryan


1 Answers

This is done for performance reasons as global lookups and method lookups are much slower than local variable lookups as they have to access at least one dictionary where as locals are list indexed.

You could reverse this optimization like:

def unquote(s):
    """unquote('abc%20def') -> 'abc def'."""
    list = s.split('%')
    res = [list[0]]
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                res.append(chr(int(item[:2], 16))
                     + item[2:])
            except ValueError:
                res.append('%' + item)
        else:
            res.append('%' + item)
    return "".join(res)

But you would find if you ran it under the profiler that it is slower.

like image 80
Dan D. Avatar answered Dec 07 '25 17:12

Dan D.