相关疑难解决方法(0)

为什么Python不能在闭包中增加变量?

在这段代码中,我可以从条形函数内部打印计数器的值

def foo():
    counter = 1
    def bar():
        print("bar", counter)
    return bar

bar = foo()

bar()
Run Code Online (Sandbox Code Playgroud)

但是当我尝试从bar函数内部递增计数器时,我得到一个UnboundLocalError错误.

UnboundLocalError: local variable 'counter' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

带有增量语句的代码片段.

def foo():
    counter = 1
    def bar():
        counter += 1
        print("bar", counter)
    return bar

bar = foo()

bar()
Run Code Online (Sandbox Code Playgroud)

您是否只在Python闭包中对外部函数中的变量具有读取权限?

python closures

38
推荐指数
2
解决办法
1万
查看次数

为什么在Python 3中未编译,重复使用的正则表达式如此之慢?

在回答这个问题时(并且已经阅读了类似问题的答案),我认为我知道Python如何缓存正则表达式.

但后来我想我会测试它,比较两种情况:

  1. 单个正则表达式的单个汇编,然后编译正则表达式的10个应用程序.
  2. 10个未编译的正则表达式的应用程序(我希望性能稍差一些,因为正则表达式必须编译一次,然后缓存,然后在缓存中查找9次).

然而,结果是惊人的(在Python 3.3中):

>>> import timeit
>>> timeit.timeit(setup="import re", 
... stmt='r=re.compile(r"\w+")\nfor i in range(10):\n r.search("  jkdhf  ")')
18.547793477671938
>>> timeit.timeit(setup="import re", 
... stmt='for i in range(10):\n re.search(r"\w+","  jkdhf  ")')
106.47892003890324
Run Code Online (Sandbox Code Playgroud)

这慢了5.7倍!在Python 2.7中,仍然增加了2.5倍,这也超出了我的预期.

在Python 2和3之间是否更改了正则表达式的缓存?文档似乎没有暗示这一点.

python regex caching

17
推荐指数
1
解决办法
710
查看次数

标签 统计

python ×2

caching ×1

closures ×1

regex ×1