local variable 'uuid' referenced before assignment
Question:
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?
Answers:
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.
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?
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.