0

I want to use the name of an assigned variable and not the values in it.
Example:

y1 = 1000

y2 = y1

Goal is to get "y1" as string from y2 and not the value of 1000

I tried:

print(f"{y}")

and got 1000

Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • 6
    Python variables don't work like that. If you wanted `'y1'`, you should have set `y2 = 'y1'`. – user2357112 Jan 25 '22 at 21:27
  • 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) – Woodford Jan 25 '22 at 21:30
  • 1
    https://nedbatchelder.com/text/names.html – chepner Jan 25 '22 at 21:30
  • 2
    If your code relies on the names of variables then usually that means there's a better way to do that thing. Typically, if you want to store the names of things as strings, you'd use a `dict()` object. – Random Davis Jan 25 '22 at 21:32
  • I honestly do not understand why anyone would do this. What's your rationale behind it? –  Jan 25 '22 at 21:49

1 Answers1

0

I don't think it's possible doing what you are asking for, the way you are describing it.

Here we have the distinction between a variable and a value. By doing this: y1 = 1000, you are setting the value 1000 (int) to the variable y1. By doing this: y2 = y1, not only you are assigning the value of the variable y1 to y2, but you are also pointing to the memory address where y1 keeps 1000.

  • It's possible since Python 3.8 (`y2 = f'{y1=}'.split('=')[0]`), but there's no point in doing such a thing. –  Jan 25 '22 at 21:53
  • All right! I did not know that! – Ignacio Arizna Jan 25 '22 at 22:25
  • @cesarv: That doesn't make what the questioner is asking for possible. That's just a long-winded and inefficient way of doing `y2 = 'y1'`. You still need to hardcode the `y1` name in your `y2 = f'{y1=}'.split('=')[0]` line; you can't recover the name after performing `y2 = y1`. – user2357112 Jan 25 '22 at 22:49
  • @user2357112supportsMonica, that makes it possible, but there's NO POINT in doing such a thing. I think I was pretty clear. –  Jan 26 '22 at 01:16
  • @cesarv: The questioner wants to retrieve the string `'y1'` from `y2` after doing `y2 = y1`. Your suggestion doesn't achieve that. Your suggestion is an awkward and inefficient way of doing `y2 = 'y1'`. It doesn't work unless you already know the output you want is `'y1'`, in which case you could just write `y2 = 'y1'`. – user2357112 Jan 26 '22 at 01:23