get a list from a string

S

simon kagwe

Hi,

I have a string "distances = [[1,1,1,1],[2,2,2,2]]". I want to create a
variable called distances whose value is the list [[1,1,1,1],[2,2,2,2]]. How can
I go about that? I know I can use setattr, but how do I create the list from the
string?

Regards,
Simon
 
H

half.italian

Hi,

I have a string "distances = [[1,1,1,1],[2,2,2,2]]". I want to create a
variable called distances whose value is the list [[1,1,1,1],[2,2,2,2]]. How can
I go about that? I know I can use setattr, but how do I create the list from the
string?

Regards,
Simon

exec("distances = [[1,1,1,1],[2,2,2,2]]")

~Sean
 
S

Steven D'Aprano

exec("distances = [[1,1,1,1],[2,2,2,2]]")
Wow! So simple!

Thanks a lot. :)

Yes, and when you embed this in your web-application, using data gathered
from a web-form, the black-hat hackers will thank you for the security
hole too.

Surely a much better solution would be NOT to start with a string like
"distances = [[1,1,1,1],[2,2,2,2]]" in the first place? Where does that
string come from? If it comes from the user, at run-time, using exec is a
MAJOR security hole. If it comes from the source code, then WHY???

I wish exec and eval were hidden away in a module so they were harder (but
not impossible) to get to. Because I'm paranoid, I wish importing that
module would print an warning saying "Are you MAD??? Don't do this!!!". I
wish even more that Python would come with a built-in "make a list from a
list representation" function, but that at least is fairly easy to create:
you can modify




Here is a discussion about just how hard (that is, probably impossible) it
is to make eval safe:

http://effbot.org/zone/librarybook-core-eval.htm
 

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
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top