7

I have a problem similar to this, however I do not know what the term is

cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]
for animal in animals:
    # by animal name, I mean the variable name that's being used
    print(animal_name + str(animal))

It should print out

cat5
dog3
fish7

So I am wondering if there is an actual method or function I could use to retrieve the variable name being used as a string.

thelost
  • 695
  • 3
  • 12
  • 29

9 Answers9

15

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.
wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    I think it would be possible using traceback which I read somewhere. I could purposely cause an error with the variable and have this error put in a string then use regex to retrive the variable. – thelost Feb 03 '12 at 00:32
  • An interesting idea! I would be interested to hear if you have some success with this method. – wim Feb 03 '12 at 00:46
5

Use a dictionary rather than a bunch of variables.

animals = dict(cat=5, dog=3, fish=7)

for animal, count in animals.iteritems():
    print animal, count

Note that they may not (probably won't) come out in the same order you put them in. You can address this using collections.ordereddict or just by sorting the keys if you merely need them in a consistent order:

for animal in sorted(animals.keys()):
    print animal, animals[animal]
kindall
  • 178,883
  • 35
  • 278
  • 309
2

Well, work with f-strings:

cat = 5

print(f"{cat=}")

Result:

cat=5

fadop3
  • 21
  • 4
0

A different form of fadop3's answer

cat = 5
cat = '%s' % cat

This turns the cat variable into a string.

Haddock-san
  • 745
  • 1
  • 12
  • 25
0

It was too old question, but for verity we can use

[name for name, obj in globals().items() if eval(name) in animals]

  • we get
['cat', 'dog', 'fish']
  • data
cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]
Mohamed Desouky
  • 4,340
  • 2
  • 4
  • 19
0

I would change to using a dictionary variable that would let you easily map string names to values.

animalDict['cat'] = 5
animalDict['dog'] = 3

Then you can interate through the keys and print out what you want.

TJD
  • 11,800
  • 1
  • 26
  • 34
0
myAnimals = {'cat':5,'dog':3,'fish':7}
animals = ['cat','dog','fish']
for animal in animals:
    if myAnimals.has_key(animal): print animal+myAnimals(animal)
DonCallisto
  • 29,419
  • 9
  • 72
  • 100
0

Instead of putting the variables into a list, I would put them into a dictionary.

d={}
d['cat']=5
d['dog']=3
d['fish']=7

for item in d.keys():
  print item+' '+d[item]
CoffeeRain
  • 4,460
  • 4
  • 31
  • 50
0

You're confusing the variable name with the string of the animal name:

In here:

cat = 7 

cat is the variable, 7 its value

In:

cat = 'cat'

cat is still the variable and 'cat' is the string with the animal name. You can put whatever string you like inside cat even cat = 'dog'.

Now back to your problem: you want to print out the name of an animal and a correposnding number.

To pair name and number the best choice is to use a dict, a dictionary. the { and } are representing a dict (just to be complete also a set in some cases):

d = {3: 'cat', 5: 'dog', 7: 'fish'}

d is your variable. {3: 'cat', 5: 'dog', 7: 'fish'} is your dictionary. 3, 5, 7 are the keys of such dictionary and 'cat', 'dog', 'fish' are the corresponding values.
Now you nedd to iterate on this dictionary. That can be done calling d.items():

d = {3: 'cat', 5: 'dog', 7: 'fish'}
for key,value in d.items():
    print(value, key)

I reversed the value, key order diring printing to print the name before the number.

Rik Poggi
  • 28,332
  • 6
  • 65
  • 82