0

We know that in python you can get the name of a defined function: eg.

def f(x):
    return x

print(f"we've just defined function {f.__name__}")

Let's say i create a variable:

x = 4

Now at some point i would like to do:

print(f"you have defined a variable named {x.__name__}")

But the syntax above gives an error because x doesn't have such an attribute.

Is there a way to get the variable's name from its value, just as we can do with the value of a defined function ?

moctarjallo
  • 1,479
  • 1
  • 16
  • 33
  • Does this answer your question? [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – PacketLoss Sep 22 '20 at 05:03
  • `a=b=c=1`. Which name should be returned for value 1? Objects can have multiple names. – Mark Tolonen Sep 22 '20 at 05:03
  • 1
    What are you trying to do? Your example can be simplified to `print("you have defined a variable named x")` since you already know the variable name `x`, but I doubt that this is what you want. – Selcuk Sep 22 '20 at 05:07
  • add complete code here so else can understand what you doing – Mr Coder Sep 22 '20 at 05:16
  • Your code can monitor the contents of `globals()` for the appearance of entries it does not already know about. – BoarGules Sep 22 '20 at 07:30

1 Answers1

0

In the interpreter, you can simply call dir() and it will output all of the variables currently initialized in the interpreter. You can also show them using a script by writing

print(dir())

An example of this output is shown below:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'numpy', 'plt', 'polar', 'r', 'theta', 'time', 'x', 'y']

Note that each of these variables are listed in alphabetical order, and can be iterated through as a list object.