#!/usr/bin/env python3 # -*- coding: utf-8 -*- def check_test(): print('*globals().keys() не меняется ->', *globals().keys()) print(' До всего') print('locals() ->', locals()) print('dir() ->', dir()) print(' До "exec"') print('a = 5') a = 5 print('locals() ->', locals()) print('dir() ->', dir()) exec(''' print(' Внутри "exec"') print('b = 3') b = 3 print('locals() ->', locals()) print('dir() ->', dir()) print('a ->', a) print('locals()["b"] ->', locals()['b']) print('b ->', b) ''') # , globals(), locals() print(' После "exec"') print('locals() ->', locals()) print('dir() ->', dir()) print('a ->', a) print('locals()["b"] ->', locals()['b']) print(end='b -> ') try: print(b) except Exception as e: print(e) exec(''' print(' Внутри второго "exec"') print('b ->', b) ''') print(' После второго "exec"') print(end='b -> ') try: print(b) except Exception as e: print(e) if __name__ == '__main__': check_test()
*globals().keys() не меняется -> __name__ __doc__ __package__ __loader__ __spec__ __builtins__ __file__ check_test
До всего
locals() -> {}
dir() -> []
До "exec"
a = 5
locals() -> {'a': 5}
dir() -> ['a']
Внутри "exec"
b = 3
locals() -> {'a': 5, 'b': 3}
dir() -> ['a', 'b']
a -> 5
locals()["b"] -> 3
b -> 3
После "exec"
locals() -> {'a': 5, 'b': 3}
dir() -> ['a', 'b']
a -> 5
locals()["b"] -> 3
b -> name 'b' is not defined
Внутри второго "exec"
b -> 3
После второго "exec"
b -> name 'b' is not defined