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?
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).
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 ...
try: thevariable except NameError: print("well, it WASN'T defined after all!") else: print("sure, it was defined.")
'a' in vars() or 'a' in globals()
if you want to be pedantic, you can check the builtins too'a' in vars(__builtins__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With