-4

Let's say I have:

a = (1,2,3,4,5)
b = (2,4,5,6,7)
c = (a,b)

where a, b and c are tuples. How do I get the name of 'a' and 'b'? I was trying with:

for x in c:
    print(type(x).__name__)

but it gives me tuple

mitra
  • 37
  • 4
  • 8
    Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Apr 08 '21 at 16:13
  • 4
    There's a subtle distinction here. The tuple doesn't *have* a name; it may have one (or more) names that *refer* to it, but an object doesn't track those names. – chepner Apr 08 '21 at 16:14
  • What if you do: `z = a; c = (a, b)`? What do you expect the names inside `c` to be? – quamrana Apr 08 '21 at 16:14
  • 1
    `a` and `b` are not names given to the tuples, it's rather the other way around: the tuples are assigned to these names. The tuples themselves are in no way connected to these names. Could you use a `dict` instead? E.g.: `c = {"a": a, "b": b}` and if you need only the values, just use `c.values()`. – Valentin Kuhn Apr 08 '21 at 16:15
  • Your loop would then be: `for k,v in c: print(k)` with k the key (name) and v the value (tuple in this case). – Valentin Kuhn Apr 08 '21 at 16:16
  • 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) – Tomerikoo Apr 08 '21 at 16:18

1 Answers1

-2

The python-varname package allows you to inspect variable names in general. Maybe that will help you. You can get it with pip install varname. Its GitHub is here and the README there provides usage examples.

edit: actually, for your use case, the comment given by @chepner is spot-on. I'll leave this answer up in case the package is of use to someone trying to get a variable name for a different case, since it would work on for example a and b themselves. But @chepner explains exactly why getting 'a' and 'b' out of 'c' is not going to be possible.

sinback
  • 926
  • 5
  • 17
  • 3
    Aside from just being a terrible idea, `python-varname` doesn't actually do what you think it does. It's based on AST inspection, so you can't do something like `for thing in stuff: print(nameof(thing))` and get the "original" names of the things in the list. You'll get `'thing'` every time. – user2357112 Apr 08 '21 at 16:19