Home  >  Article  >  Backend Development  >  How to check if a variable exists

How to check if a variable exists

anonymity
anonymityOriginal
2019-05-27 14:07:204160browse

When calling a variable, if the variable is not defined, python will report an error.

How to check if a variable exists

#The solution is also very simple, which is to assign a null value to the variable in advance.

But you can also determine whether a variable name has been defined by calling the system's built-in function. There are 3 built-in functions that can be implemented.

res1 = 'test' in locals().keys()
res2 = 'test' in dir()
res3 = 'test' in vars().keys()
print(res1,res2,res3)  # 变量test暂时还没有定义,返回False
test = ""  # 定义变量test
res4 = 'test' in locals().keys()
res5 = 'test' in dir()
res6 = 'test' in vars().keys()
print(res4,res5,res6)  # 变量test已经被定义了,返回True

Above, if you need to call a variable that is not sure whether it has been defined, you can first use the above function to add a judgment.

The above is the detailed content of How to check if a variable exists. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn