-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
62 lines (41 loc) · 1.08 KB
/
Copy pathexample.py
File metadata and controls
62 lines (41 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""Scope — LEGB rule, global, and nonlocal."""
x = "module-level"
def outer():
x = "enclosing"
def inner():
nonlocal x
x = "inner modified"
print(f" inner x: {x}")
def reader():
print(f" reader x (enclosing): {x}")
reader()
inner()
print(f" outer x after inner: {x}")
def global_demo():
global x
print(f" before global assign: {x}")
x = "global modified"
def legb_demo():
builtin_name = "local shadows nothing yet"
print(f" len is: {len}") # Built-in
print(f" local: {builtin_name}")
counter = 0
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
if __name__ == "__main__":
print("=== LEGB: Local, Enclosing, Global, Built-in ===")
print(f"module x: {x}")
outer()
print("\n=== global ===")
global_demo()
print(f"module x after: {x}")
print("\n=== legb_demo ===")
legb_demo()
print("\n=== factory with nonlocal ===")
inc = make_counter()
print(inc(), inc(), inc())