0

I have a Twisted application where I need to generate unique ids. If I import uuid and then try str(uuid.uuid4()), it says "exceptions.UnboundLocalError: local variable 'uuid' referenced before assignment".

It works fine if I do import uuid as myuuid

What exactly is the cause of this? Is there a Twisted way of using uuids instead of the uuid module directly?

Glyph
  • 31,152
  • 11
  • 87
  • 129
Crypto
  • 1,217
  • 3
  • 17
  • 33

1 Answers1

4

Don't be afraid of Python's interactive interpreter:

>>> 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()
>>> 

It can tell you a lot with just a little experimentation.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122