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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With