Python 3 的 unquote 是 chr 和 int 的别名的原因?
Reason for Python 3's unquote making an alias of chr and int?
在Python3的函数unquote
中(来自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)
我们有 2 个最先执行的行:
mychr = chr
myatoi = int
及其用法:
...
myappend(mychr(myatoi(item[:2], 16))
+ item[2:])
...
如果这两个函数只在这个函数中使用,为什么要使用别名?它们可以很容易地换成 chr
和 int
.
这样做是出于性能原因,因为全局查找和方法查找比局部变量查找慢得多,因为它们必须访问至少一个字典,其中局部变量是列表索引的。
您可以像这样反转此优化:
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)
但是如果你 运行 它在分析器下,你会发现它更慢。
在Python3的函数unquote
中(来自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)
我们有 2 个最先执行的行:
mychr = chr
myatoi = int
及其用法:
...
myappend(mychr(myatoi(item[:2], 16))
+ item[2:])
...
如果这两个函数只在这个函数中使用,为什么要使用别名?它们可以很容易地换成 chr
和 int
.
这样做是出于性能原因,因为全局查找和方法查找比局部变量查找慢得多,因为它们必须访问至少一个字典,其中局部变量是列表索引的。
您可以像这样反转此优化:
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)
但是如果你 运行 它在分析器下,你会发现它更慢。