Check the scope of local variables with the Python locals function.
locals()
From help
locals()
Return a dictionary containing the current scope's local variables.
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
I feel unfamiliar with Python. .. .. ..
g0_val = "g0"
def func1():
func1_val = "f1"
class Class1():
class1_val = "c1"
def func2():
func2_val = "f2"
class Class2():
class2_val = "c2"
print("class2-locals",locals())
for y2 in range(1):
range2_val = "r2"
def func3():
func3_val = "f3"
class Class3():
class3_val = "c3"
for y3 in range(1):
range3_val = "r3"
print("fun3-locals",locals())
func3()
print("fun2-locals",locals())
func1()
func2()
It became as follows.
C:\_qiita\python_etc\_locals>python test_locals.py
class2-locals {'__module__': '__main__', '__qualname__': 'func2.<locals>.Class2', 'class2_val': 'c2'}
fun3-locals {'func3_val': 'f3', 'Class3': <class '__main__.func2.<locals>.func3.<locals>.Class3'>, 'y3': 0, 'range3_val': 'r3'}
fun2-locals {'func2_val': 'f2', 'Class2': <class '__main__.func2.<locals>.Class2'>, 'y2': 0, 'range2_val': 'r2', 'func3': <function func2.<locals>.func3 at 0x000002B3CED922F0>}
The following was confirmed.
If you express it in words ** Only functions and classes have block scope ** Is not it.
I hope it is expressed by a proper noun. .. ..
Nothing in particular. If you have any comments, please let us know.
(What I really wanted to consider was what would happen if I moved a lot of the code to a function. Perhaps, if I didn't do anything special, I just felt that the scope was local and that wasn't a problem. )
Recommended Posts