0 votes
1 view
in Python by (47.8k points)

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?

2 Answers

0 votes
by (107k points)

If you want to know whether a variable has been set at a particular place in the code at runtime you can use the following piece of code:-

         

try:

thevariable

except NameError:

print("well, it WASN'T defined after all!")

else:

print("sure, it was defined.")

0 votes
by (20.3k points)

Try using this:

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

But, if you want to be pedantic, then you can check the builtins too like this:

'a' in vars(__builtins__)

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...