方法1:使用globals()函数
globals()
函数返回一个字典,表示当前的全局符号表。我们可以检查变量名是否在此字典中。
# 检查全局变量是否存在
if 'app_config' in globals():
print("全局变量 'app_config' 已存在")
else:
print("全局变量 'app_config' 未定义")
# 检查全局变量是否被赋值
if 'app_config' in globals() and globals()['app_config'] is not None:
print("全局变量 'app_config' 已被赋值")
else:
print("全局变量 'app_config' 未被赋值")
发表评论