0

Can a Python instance get the name of the variable which is used to access the object?

This example code shows what I need:

foo=MyClass()
foo.get_name() --> 'foo'

bar=foo
bar.get_name() --> 'bar'

I know that this is black magic and not clean code. I just want to know if it is possible.

I know that bar.__name__ returns the name, but I need it inside an own method.

How can get_name() be implemented?

This is not a duplicate of questions which answer is __name__

guettli
  • 25,042
  • 81
  • 346
  • 663
  • This question is a duplicate of a duplicate. – Jayanth Koushik Apr 30 '14 at 06:55
  • 2
    What if the object is referenced by more than one name? Or is referenced in a list along with other instances? Names in Python are really just tags, if you need to do this you're probably doing something wrong. – jonrsharpe Apr 30 '14 at 07:10
  • @jonrsharpe the above example contains the answer to the question "hat if the object is referenced by more than one name?". It contains what should happen, the solution is not known to me. – guettli Apr 30 '14 at 07:35
  • 1
    But your `get_name` method would return different results _for the same instance_ depending on from what variable it was called. What about `MyClass().get_name()` or `lst = [MyClass()]; lst[0].get_name()`? As jon suggested, what do you need this for? Maybe there's a better way, e.g. using a dictionary. – tobias_k Apr 30 '14 at 08:09
  • @tobias_k I ask this question, since I don't know a solution. Maybe it is possible to implement get_name()? – guettli Apr 30 '14 at 08:14
  • Probably you could use the `inspect` module and look for the item in `inspect.stack()` that has `*.get_name()` in its line... but really, you rather shouldn't. – tobias_k Apr 30 '14 at 08:41
  • 3
    @guettli perhaps it would help if you explained *why* you feel the need to do this? What are you trying to achieve? Then we might be able to provide a better overall solution. If you could implement `get_name()`, what would you do with it? – jonrsharpe Apr 30 '14 at 09:05

0 Answers0