If "x" exists, then print "x exists".
I ask this because I always get this error:
UnboundLocalError at /settings/
local variable 'avatarlink' referenced before assignment
Why do you need to know? If the code breaks because of this, it's probably because the code is wrong anyway and needs to be fixed.
That said, try checking if 'x' in locals() or if 'x' in globals(), as appropriate to where you're expecting it to be.
if. Just put the variable's name inside a try with and except NameError:. Beside being easier, you're checking for existence the way Python does, not restricting it to locals, 'globals`, etc.As they say in Python, "it's better to ask forgiveness than permission". So, just try and access the variable, and catch the error if it doesn't exist.
try:
x
print "x exists"
except UnboundLocalError:
print "x doesn't exist"
However, I would really like to know why you think you need to do this. Usually, you would always set the variable before checking its value.
UnboundLocalError is a subtype of NameError. It would only be raised if x was determined at compile time to be a local variable, but hasn't yet been assigned. This can only happen inside a function, and only if there is an assignment to the name elsewhere in the function and there is no corresponding global or nonlocal declaration. Otherwise, a generic NameError will result.
locals(),globals(), don't catchUnboundLocalError, fix your code instead. Please, read links on scopes, namespaces, naming, and binding in Python provided in the answer stackoverflow.com/questions/575196/…