Skip to content

Commit 8b41738

Browse files
committed
variable scope explained
1 parent ebb9c7f commit 8b41738

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
# No Surprise
3+
>>> b = 6
4+
>>> def f(a):
5+
... print(a)
6+
... print(b)
7+
>>> f(3)
8+
3
9+
6
10+
11+
# This may suprise you
12+
>>> b = 6
13+
>>> def f1(a):
14+
... print(a)
15+
... print(b)
16+
... b = 9
17+
18+
By calling f1(3) you will get
19+
3
20+
Traceback(most recent call last):
21+
File "<stdin>", line 1 ...
22+
File "<stdin>", line 3 ...
23+
UnboundLocalError: local variable 'b' referenced before assignment
24+
25+
It is Unbound(not assigned) Local(inside the function) Error!
26+
27+
The fact is:
28+
1. When Python compiles the body of the function, it decides that b is a local
29+
variable because it is assigned within the function
30+
2. It will fetch b from the local environment and find it is unbound
31+
3. It is a design choice
32+
Python does not require you to declare variables
33+
but assumes that a variable assigned in the body of a function is local
34+
"""
35+
36+
if __name__ == "__main__":
37+
import doctest
38+
doctest.testmod()

0 commit comments

Comments
 (0)