ConfigParser & converting strings to lists

Chris Liechti cliechti at gmx.net
Sun Jun 23 08:50:09 EDT 2002


"Edward K. Ream" <edream at tds.net> wrote in news:3D159F06.2154D3F3 at tds.net:

> To complete this topic, let me restate the problem and JohnJacob's
> elegant solution.
> 
> Suppose files is a list of strings, and we have written a configuration
> section like this:
> 
>   config = ConfigParser.ConfigParser()
>   config.set("recent files", "recentFiles, files)
> 
> Then the elegant way of retrieving files _as a list_ is:
> 
>   files = eval(config.get("recent files", "recentFiles"))

it isn't that elegant i tend to call that sloppy ;-) the problem is that 
you execute arbitrary python expressions and you hope to get a list. but 
that is not sure, the user could have edited the config file.
exec and eval are always a risk in your code. e.g they could rise any 
exception because you don't know what they realy execute.

the split version is much more secure. you could also try a pickle. witch 
pickle.dumps you can get a string and reterive the old object using loads() 
but that isn't as secure as split.

if thats all too complicated, use your version with individual names 
"file1", "file2", ... it's much saver for a progrom that you release in the 
wild.

chris

PS you mentioned you see double backslashes. maybe you looked at the repr 
of a string:
>>> s = "he\tllo"
>>> repr(s)
"'he\\tllo'"
>>> str(s)
'he\tllo'
>>> print s
he	llo
>>> 

as you can see there is not realy a double backslash...

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list