Most Pythonic way to store (small) configuration
Steven D'Aprano
steve at pearwood.info
Wed Aug 5 10:08:13 EDT 2015
On Wed, 5 Aug 2015 11:46 pm, Rustom Mody wrote:
> On Sunday, August 2, 2015 at 3:44:51 PM UTC+5:30, Cecil Westerhof wrote:
>> There are a lot of ways to store configuration information:
>> - conf file
>> - xml file
>> - database
>> - json file
>> - and possible a lot of other ways
>
> One that I dont think has been mentioned:
> ast.literal_eval
Probably because it doesn't work :-)
py> import ast
py> s = "x = 23" # pretend I read this line from a file
py> ast.literal_eval(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.3/ast.py", line 47, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/local/lib/python3.3/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
x = 23
^
SyntaxError: invalid syntax
You might be able to build Yet Another Config Format using literal_eval as a
building block, for evaluating values, but *in and of itself* it isn't a
way to store config information, any more than
int
float
or any other function which takes a string and evaluates it as a Python
primitive or built-in type.
However, there are at least config formats in the standard library which I
believe we've missed: shelve, and plistlib.
help(shelve)
A "shelf" is a persistent, dictionary-like object. The difference
with dbm databases is that the values (not the keys!) in a shelf can
be essentially arbitrary Python objects -- anything that the "pickle"
module can handle. This includes most class instances, recursive data
types, and objects containing lots of shared sub-objects. The keys
are ordinary strings.
help(plistlib)
The property list (.plist) file format is a simple XML pickle supporting
basic object types, like dictionaries, lists, numbers and strings.
Usually the top level object is a dictionary.
--
Steven
More information about the Python-list
mailing list