[Tutor] What's in a name?

Danny Yoo dyoo at hashcollision.org
Fri Jan 3 06:57:20 CET 2014


On Thu, Jan 2, 2014 at 9:22 PM, Keith Winston <keithwins at gmail.com> wrote:
> I've got the beginner's version of a question I think Denis asked
> recently...
>
> If I'm iterating a variable through a series of list names, for future
> processing, I would like to print the name of the list the variable is set
> to in a given moment... i.e.
>
> for i in [alist, blist, clist]
>     i[3] = "okey dokey "
>     print(i[3], i.name)  # this is definitely not the way to do it...


One of the things you can do is make the following idea more concrete:

    You want some _name_ associated with a _value_.

In that case, you want the name 'alist' to be closely associated with
the list that goes by that name.


You can do this kind of thing without being specific to any
particularities about Python.  Directly: put that information in a
data structure, such as a dictionary.  Put the name _in_ the value.

For example:

##########################
class Person(object):
    def __init__(self, name):
        self.name = name

    def sayHi(self):
        print("this is " + self.name + "; hello!")

people = {'frank' : Person('frank'),
          'sally' : Person('sally'),
          'timothy' : Person('timothy')}

for nick, p in people.items():
    print(repr(nick) + " says: ")
    p.sayHi()
##########################


There is a reason why you might want to save the name as part of the
value, rather than to try to get that from the name of the variable.
Here's one reason: sometimes people go by different names.

##########################
tim = people['timothy']
tiny_tim = tim
tym = tim
# ... see http://en.wikipedia.org/wiki/Timothy_(name)
##########################

in which case, if we try to print out this person later on, which name
would you like to see?  Rather than guess, we might as well use the
name that timothy identifies himself with.


Good luck!


More information about the Tutor mailing list