0

Is it possible to make a python function that check if variable exist ?

I tried this but its dont working :

def tst(x):
 try: x
 except NameError:
  x = raw_input("%s: " % x)
 return x

Do there's a way for do that , or i will everytime have to try and except error ?

Thx

user7426942
  • 31
  • 1
  • 1
  • 4
    You pass a variable to the function which checks whether this variable exists... Where's the logic??? – ForceBru Jan 16 '17 at 18:40
  • You're obviously new (1 reputation point) so it's a bit harsh to vote your question down. But people have because it doesn't show basic research or understanding of Python. It's important to do a bit of homework before asking questions. Your issue is that you're defining a function to test a variable. The function can only test the argument (locally bound name for the variable passed to it). So it will never fail in the function. It will fail at the site where the function is called if the variable isn't defined. – bmacnaughton Jan 16 '17 at 18:50

2 Answers2

1

It is possible, but you should probably consider what you're trying to accomplish, you could use something like this:

if x in locals() or x in globals():
    ...
Francisco
  • 10,918
  • 6
  • 34
  • 45
0

The problem with this is that python will declare a new variable x so you will never encounter a NameError.

A solution for this already exists

Community
  • 1
  • 1
Imran Ali
  • 104
  • 13
  • If a solution already exists within the Stack network, please flag the question as a duplicate :) – Sterling Archer Jan 16 '17 at 18:43
  • Thanks, and done. – Imran Ali Jan 16 '17 at 18:44
  • It's not the same question. He's asking how to write a function that tests if a variable exists not how to check if a variable exists. The problem is if you pass the potentially undefined variable to the function, how do you even refer to it from inside the function – slashdottir Oct 09 '20 at 21:59