Most Pythonic way to store (small) configuration
steve at pearwood.info
Wed Aug 5 16:08:13 CEST 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:
Probably because it doesn't work :-)
py> import ast
py> s = "x = 23" # pretend I read this line from a file
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
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.
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.
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.
More information about the Python-list