Last active
September 23, 2022 22:14
-
-
Save amotl/4d8bc928d781a5d0fbc7f404396f8417 to your computer and use it in GitHub Desktop.
Exercise serializing `NoneType` values with Python's `toml`, `tomlkit`, and `tomli-w` packages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
About | |
===== | |
Exercise serializing `NoneType` values with Python's `toml`, `tomlkit`, and `tomli-w` packages. | |
Currently, it croaks with both `tomlkit` and `tomli-w`: | |
- `tomlkit==0.11.4`: `ValueError: Invalid type <class 'NoneType'>` | |
- `tomli-w==1.0.0`: `TypeError: Object of type <class 'NoneType'> is not TOML serializable` | |
Evaluation | |
========== | |
First of all, there is no `NULL` value in TOML, and there never will be. | |
- https://github.com/toml-lang/toml/issues/921 | |
- https://twitter.com/mitsuhiko/status/1346455555435593729 | |
While `tomli-w` still writes the file until the exception is raised, `tomlkit` | |
just writes an empty file. Only `toml` ignores `NoneType` values and just | |
skips them. | |
Usage | |
===== | |
:: | |
# Install | |
pip install pytest toml tomlkit tomli-w | |
# Invoke | |
pytest test_toml_nonetype.py | |
References | |
========== | |
- https://github.com/isarengineering/SecPi/issues/25 | |
- https://github.com/isarengineering/SecPi/pull/27 | |
- https://github.com/sdispater/tomlkit/issues/240 | |
- https://github.com/hukkin/tomli-w/issues/39 | |
""" | |
import pytest | |
import toml | |
import tomli_w | |
import tomlkit | |
DATA_IN = {"foo": 42, "bar": None, "baz": "qux"} | |
TOML_OUT = 'foo = 42\nbaz = "qux"' | |
@pytest.mark.parametrize("module", [toml, tomlkit]) | |
def test_write(tmp_path, module): | |
filename = tmp_path.joinpath("test.toml") | |
with open(filename, "w") as config_file: | |
try: | |
module.dump(DATA_IN, config_file) | |
except Exception: | |
pass | |
with open(filename, "r") as config_file: | |
payload = config_file.read().strip() | |
assert payload == TOML_OUT | |
def test_write_tomli(tmp_path): | |
""" | |
`tomli-w` needs file handle to be opened in binary mode. | |
""" | |
filename = tmp_path.joinpath("test.toml") | |
with open(filename, "wb") as config_file: | |
try: | |
tomli_w.dump(DATA_IN, config_file) | |
except Exception: | |
pass | |
with open(filename, "r") as config_file: | |
payload = config_file.read().strip() | |
assert payload == TOML_OUT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment