By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,360 Members | 2,199 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,360 IT Pros & Developers. It's quick & easy.

automatic naming of variables to create objects

P: n/a
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).
Is there a better way?
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Jul 18 '05 #2

P: n/a
Thanks for that, Peter.
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.