在赋值之前引用的局部变量'uuid'

时间:2014-02-20 01:10:28

标签: python

我有一个Twisted应用程序,我需要生成唯一的ID。如果我导入uuid然后尝试str(uuid.uuid4()),它会说“exceptions.UnboundLocalError:在赋值之前引用的局部变量'uuid'。”

如果我import uuid as myuuid

,它可以正常工作

究竟是什么原因造成的?是否存在直接使用uuids代替uuid模块的Twisted方式?

1 个答案:

答案 0 :(得分:3)

不要害怕Python的交互式解释器:

>>> import uuid
>>> def foo():
...     uuid = uuid.uuid4()
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'uuid' referenced before assignment
>>> def bar():
...     uuidValue = uuid.uuid4()
... 
>>> bar()
>>> 
>>> someGlobal = 10
>>> def baz():
...     someGlobal = someGlobal + 1
... 
>>> baz()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in baz
UnboundLocalError: local variable 'someGlobal' referenced before assignment
>>> def quux():
...     someLocal = someGlobal + 1
... 
>>> quux()
>>> 

通过一些实验,它可以告诉你很多。