Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if variable is defined in Python [duplicate]

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:     a = 42  # is "a" defined here?  if other_condition:     del a  # is "a" defined here? 
like image 532
user102008 Avatar asked Oct 20 '09 05:10

user102008


People also ask

How do you check if a variable is not empty in Python?

Use the is not operator to check if a variable is not Null in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

How do you fix a undefined variable in Python?

There are a few ways to fix an undefined variable: (1) You can rename the variable or variable set so that it matches what you have used in the topic; (2) you can re-insert the variable in the topic so that it uses an existing variable set/variable name, (3) you can add the undefined variable to the project as a new ...


2 Answers

try:     thevariable except NameError:     print("well, it WASN'T defined after all!") else:     print("sure, it was defined.") 
like image 190
Alex Martelli Avatar answered Oct 07 '22 01:10

Alex Martelli


'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)

like image 23
John La Rooy Avatar answered Oct 06 '22 23:10

John La Rooy