automatic naming of variables to create objects

R

r holland

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?
 
P

Peter Otten

r said:
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:
.... setattr(__main__, name, "set using setattr()")
........ globals()[name] = "set using the globals() dictionary"
....
Is there a better way?
.... setattr(ns, name, "make your own namespace")
....
This doesn't pollute the global namespace and reduces the risk of name
clashes.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top