Skip to content

Commit 8e34c35

Browse files
committed
Added example and link to faq for UnboundLocalError in reference
1 parent 909868d commit 8e34c35

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

Doc/faq/programming.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ Yes. The coding style required for standard library modules is documented as
111111
Core Language
112112
=============
113113

114+
.. _faq-unboundlocalerror:
115+
114116
Why am I getting an UnboundLocalError when the variable has a value?
115117
--------------------------------------------------------------------
116118

Doc/reference/executionmodel.rst

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,23 @@ used, an :exc:`UnboundLocalError` exception is raised.
125125
If a name binding operation occurs anywhere within a code block, all uses of the
126126
name within the block are treated as references to the current block. This can
127127
lead to errors when a name is used within a block before it is bound. This rule
128-
is subtle. Python lacks declarations and allows name binding operations to
128+
is subtle::
129+
130+
>>> x = 1
131+
>>> def new_scope():
132+
... print(x)
133+
... x = 2
134+
...
135+
>>> new_scope()
136+
Traceback (most recent call last):
137+
File "<stdin>", line 1, in <module>
138+
File "<stdin>", line 2, in new_scope
139+
UnboundLocalError: local variable 'x' referenced before assignment
140+
141+
Python lacks declarations and allows name binding operations to
129142
occur anywhere within a code block. The local variables of a code block can be
130143
determined by scanning the entire text of the block for name binding operations.
144+
See also :ref:`the FAQ entry on UnboundLocalError <faq-unboundlocalerror>`.
131145

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

0 commit comments

Comments
 (0)