[Tutor] define vars by iteration

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Oct 19 19:45:00 CEST 2005



On Wed, 19 Oct 2005, Luke Jordan wrote:

> I've got a bunch of pickled class instances with
> self.name<http://self.name/>attributes, and I would like to assign the
> instances themselves to variables
> named whatever is stored in self.name <http://self.name/> using a function.
> "Can't assign to literal", right? Is there a way to do this?

Hi Luke,

It's technically possible to do this, but discouraged.  The reason it's
not so safe is because some of those names might collide with your own
program's names, or with the builtins.  So if you start having pickled
instances with names like 'list' or 'open', havoc is bound to ensue.

Furthermore, Python variable names have some physical restrictions that
may interfere with what you're trying to do:

######
>>> 4meUshouldnthave = 42
  File "<stdin>", line 1
    4meUshouldnthave = 42
                   ^
SyntaxError: invalid syntax
######

(For the gory details on what's allowed in a name "identifier", see:
http://www.python.org/doc/ref/identifiers.html)


A safer way to do that I think you want is to use a separate dictionary
container for those instances.  As a concrete example:

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

people_names = ['fred', 'barney', 'wilma', 'betty']
people = {}
for name in people_names:
    people[name] = Person(name)
######

Rather than using a direct variable name to refer to the person, we can go
an indirect route, and refer to the corresponding entry in the 'people'
dictionary.  Does this make sense?  This is safer because there's no
potential to munge up the toplevel, plus the 'name' keys won't have the
restrictions that Python variable names have.


Hope this helps!



More information about the Tutor mailing list