Skip to content
Snippets Groups Projects
Commit 482efc54 authored by Martin Vejnár's avatar Martin Vejnár
Browse files

Merge pull request #8 from ntrepid8/feature/write-null-values-as-comments

Feature/write null values as comments
parents e39c7be1 422c47fb
No related branches found
No related tags found
No related merge requests found
build/
dist/
pytoml.egg-info/
venv/
.idea/
__pycache__/
......@@ -27,6 +27,16 @@ Use `dump` or `dumps` to serialize a dict into TOML.
>>> print toml.dumps(obj)
a = 1
## tests
To run the tests update the `toml-test` submodule:
$ git submodule update --init --recursive
Then run the tests:
$ python test/test.py
[1]: https://github.com/toml-lang/toml
[2]: https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md
......@@ -5,16 +5,20 @@ if sys.version_info[0] == 3:
long = int
unicode = str
def dumps(obj):
fout = io.StringIO()
dump(fout, obj)
return fout.getvalue()
_escapes = { '\n': 'n', '\r': 'r', '\\': '\\', '\t': 't', '\b': 'b', '\f': 'f', '"': '"' }
_escapes = {'\n': 'n', '\r': 'r', '\\': '\\', '\t': 't', '\b': 'b', '\f': 'f', '"': '"'}
def _escape_string(s):
res = []
start = 0
def flush():
if start != i:
res.append(s[start:i])
......@@ -34,14 +38,17 @@ def _escape_string(s):
flush()
return '"' + ''.join(res) + '"'
def _escape_id(s):
if any(not c.isalnum() and c not in '-_' for c in s):
return _escape_string(s)
return s
def _format_list(v):
return '[{}]'.format(', '.join(_format_value(obj) for obj in v))
def _format_value(v):
if isinstance(v, bool):
return 'true' if v else 'false'
......@@ -74,6 +81,7 @@ def _format_value(v):
else:
raise RuntimeError(v)
def dump(fout, obj):
tables = [((), obj, False)]
......@@ -92,6 +100,10 @@ def dump(fout, obj):
tables.append((name + (k,), v, False))
elif isinstance(v, list) and v and all(isinstance(o, dict) for o in v):
tables.extend((name + (k,), d, True) for d in reversed(v))
elif v is None:
# based on mojombo's comment: https://github.com/toml-lang/toml/issues/146#issuecomment-25019344
fout.write(
'#{} = null # To use: uncomment and replace null with value\n'.format(_escape_id(k)))
else:
fout.write('{} = {}\n'.format(_escape_id(k), _format_value(v)))
......
......@@ -5,7 +5,7 @@ from setuptools import setup
setup(
name='pytoml',
version='0.1.4',
version='0.1.5',
description='A parser for TOML-0.4.0',
author='Martin Vejnár',
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment