automatic naming of variables to create objects

Peter Otten __peter__ at web.de
Thu Jun 3 12:23:36 CEST 2004


r holland wrote:

> The only way I know of to create a series of object/variable names in
> a loop is to form strings and then use exec (or eval in some cases).

Two other options:

>>> import __main__
>>> for name in "foo bar baz".split():
...     setattr(__main__, name, "set using setattr()")
...
>>> foo
'set using setattr()'
>>> for name in "foo bar baz".split():
...     globals()[name] = "set using the globals() dictionary"
...
>>> foo
'set using the globals() dictionary'
>>>

> Is there a better way?

>>> class Namespace: pass
...
>>> ns = Namespace()
>>> for name in "foo bar baz".split():
...     setattr(ns, name, "make your own namespace")
...
>>> ns.foo
'make your own namespace'
>>>

This doesn't pollute the global namespace and reduces the risk of name
clashes.

Peter




More information about the Python-list mailing list