forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal_nonlocal.py
111 lines (84 loc) · 1.26 KB
/
global_nonlocal.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
from testutils import assert_raises
# Test global and nonlocal funkyness
a = 2
def b():
global a
a = 4
assert a == 2
b()
assert a == 4
def x():
def y():
global a
nonlocal b
assert a == 4, a
b = 3
a = "no!" # a here shouldn't be seen by the global above.
b = 2
y()
return b
res = x()
assert res == 3, str(res)
def x():
global a
global a # a here shouldn't generate SyntaxError
a = 3
x()
assert a == 3
# Invalid syntax:
src = """
b = 2
global b
"""
with assert_raises(SyntaxError):
exec(src)
# Invalid syntax:
src = """
nonlocal c
"""
with assert_raises(SyntaxError):
exec(src)
# Invalid syntax:
src = """
def f():
def x():
nonlocal c
c = 2
"""
with assert_raises(SyntaxError):
exec(src)
# Invalid syntax:
src = """
def a():
nonlocal a
"""
with assert_raises(SyntaxError):
exec(src)
src = """
def f():
print(a)
global a
"""
with assert_raises(SyntaxError):
exec(src)
# class X:
# nonlocal c
# c = 2
def a():
x = 0
locals()['x'] = 3
assert x == 0
a()
def a():
x = 0
del locals()['x']
assert x == 0
a()
def a():
x = 0
b = locals()
assert b['x'] == 0
del b['x']
b = locals()
assert b['x'] == 0
a()