The simplest way is to catch an exception:
try: x except NameError: #x was not set
However it's more appropriate to simulate isset. But be aware that unlike php the variable has to be a string:
def isset(variable): return variable in locals() or variable in globals() print(isset("somevar"))
(PHP 4, PHP 5)
isset — Determine whether a variable is set
Determine whether a variable is set.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.
Returns TRUE if var exists; FALSE otherwise.
Example #1 isset() Examples
This also work for elements in arrays: