Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Added example and link to faq for UnboundLocalError in reference
  • Loading branch information
slateny committed May 22, 2022
commit 8e34c351da29bd3e6f2a159b38bc7aadcb7e9ad2
2 changes: 2 additions & 0 deletions Doc/faq/programming.rst
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ Yes. The coding style required for standard library modules is documented as
Core Language
=============

.. _faq-unboundlocalerror:

Why am I getting an UnboundLocalError when the variable has a value?
--------------------------------------------------------------------

Expand Down
16 changes: 15 additions & 1 deletion Doc/reference/executionmodel.rst
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,23 @@ used, an :exc:`UnboundLocalError` exception is raised.
If a name binding operation occurs anywhere within a code block, all uses of the
name within the block are treated as references to the current block. This can
lead to errors when a name is used within a block before it is bound. This rule
is subtle. Python lacks declarations and allows name binding operations to
is subtle::

>>> x = 1
>>> def new_scope():
... print(x)
... x = 2
...
>>> new_scope()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in new_scope
UnboundLocalError: local variable 'x' referenced before assignment

Python lacks declarations and allows name binding operations to
occur anywhere within a code block. The local variables of a code block can be
determined by scanning the entire text of the block for name binding operations.
See also :ref:`the FAQ entry on UnboundLocalError <faq-unboundlocalerror>`.

If the :keyword:`global` statement occurs within a block, all uses of the names
specified in the statement refer to the bindings of those names in the top-level
Expand Down