ローカル変数、グローバル変数でそれぞれ locals(), globals() を利用すると、変数が存在するか確認できる。
global_x = -1
def f():
local_x = 42
if "local_x" in locals():
print(local_x) # 42
if "global_x" in globals():
print(global_x) # -1
# print(local_y) # NameError: name 'local_y' is not defined
print(locals()) # {'local_x': 42}
print(globals()) # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000017918D4DCC8>,
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'exist_variable.py', '__cached__': None,
# 'global_x': -1, 'f': <function f at 0x0000017918E5FEE8>}
f()