[英]How to check in Python if a variable has been assigned or not
I would like to check, whether a variable has been assigned or not.我想检查是否已分配变量。 Based on the answers in this question Referring to the null object in Python , I tried it with
if outputVariable==None
but this does not work and throws the error "UnboundLocalError: local variable 'outputVariable' referenced before assignment". Based on the answers in this question Referring to the null object in Python , I tried it with
if outputVariable==None
but this does not work and throws the error "UnboundLocalError: local variable 'outputVariable' referenced before assignment".
I have the following code:我有以下代码:
def testMethod(assignVariable):
if assignVariable == True:
outputVariable = 5
if outputVariable==None:
outputVariable = 0
return outputVariable
returnValue = testMethod(False)
Any idea how I can check before the return statement, if outputVariable
has a value.如果
outputVariable
有值,我知道如何在 return 语句之前检查。 If it does not, it should be given a value of 0如果不是,则应将其赋值为 0
Update: Based on the accepted answer here How do I check if a variable exists?更新:根据此处接受的答案如何检查变量是否存在? , I tried the following but it was also not successfull:
,我尝试了以下但也没有成功:
def testMethod(assignVariable):
if assignVariable == True:
outputVariable = 5
if outputVariable in locals():
pass
else:
outputVariable = 0
return outputVariable
returnValue = testMethod(False)
Here is a simple way to help you:这里有一个简单的方法来帮助你:
def tryVar(var):
try:
val = var
except NameError:
return None
return val
In your code, just use tryVar(--) wherever you want to get a variable, you can check if said variable exists by simply:在您的代码中,只需在要获取变量的任何地方使用 tryVar(--) ,您就可以通过简单地检查所述变量是否存在:
if tryVar(X) is None:
>>>DO WHATEVER
Solution for python 3.8+ if you want to assign variable, and if it doesnt exist assign 0 to it in one line: python 3.8+ 的解决方案,如果要分配变量,如果它不存在,则在一行中分配 0:
Z = x if tryVar(x) is None else x:=0
this assigns the variable if its not assigned, and returns its value, additionally if you don't want to do anything with the values you can also:如果未分配变量,则分配该变量,并返回其值,此外,如果您不想对这些值做任何事情,您也可以:
x if tryVar(x) is None else x:=0
You can't check for a variable that is not defined .您无法检查未定义的变量。 Even
None
is a well-defined value for an object;即使
None
是 object 的明确值; it's a good default value in many scenarios.在许多情况下,这是一个很好的默认值。
This is the idiomatic way to achieve what you want:这是实现您想要的惯用方式:
def testMethod(assignVariable):
return assignVariable or 0
returnValue = testMethod(False)
You can avoid that intermediate variable as it is not adding any value except being a placeholder;您可以避免使用该中间变量,因为它除了作为占位符之外没有添加任何值; function is optional if it's for one-time use.
function 是一次性使用的可选。 Python takes care of all these checks internally.
Python 在内部负责所有这些检查。 There is a ternary operator also if you need one.
如果您需要,还有一个三元运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.