You are basically asking "How can my code discover the name of an object?"
def animal_name(animal):
# here be dragons
return some_string
cat = 5
print(animal_name(cat)) # prints "cat"
A quote from Fredrik Lundh (on comp.lang.python) is particularly appropriate here.
The same way as you get the name of that cat you found on your porch:
the cat (object) itself cannot tell you its name, and it doesn’t
really care — so the only way to find out what it’s called is to ask
all your neighbours (namespaces) if it’s their cat (object)…
….and don’t be surprised if you’ll find that it’s known by many names,
or no name at all!
Just for fun I tried to implement animal_name
using the sys
and gc
modules, and found that the neighbourhood was also calling the object you affectionately know as "cat", i.e. the literal integer 5, by several names:
>>> cat, dog, fish = 5, 3, 7
>>> animal_name(cat)
['n_sequence_fields', 'ST_GID', 'cat', 'SIGTRAP', 'n_fields', 'EIO']
>>> animal_name(dog)
['SIGQUIT', 'ST_NLINK', 'n_unnamed_fields', 'dog', '_abc_negative_cache_version', 'ESRCH']
>>> animal_name(fish)
['E2BIG', '__plen', 'fish', 'ST_ATIME', '__egginsert', '_abc_negative_cache_version', 'SIGBUS', 'S_IRWXO']
For unique enough objects, sometimes you can get a unique name:
>>> mantis_shrimp = 696969; animal_name(mantis_shrimp)
['mantis_shrimp']
So, in summary:
- The short answer is: You can't.
- The long answer is: Well, actually, you sometimes can - at least in the CPython implementation. To see how
animal_name
is implemented in my example, look here.
- The correct answer is: Use a
dict
, as others have mentioned. This is the best choice when you actually need to use the name <--> object association.