Skip to content

Commit

Permalink
Merge pull request #45 from apollo13/python-toml
Browse files Browse the repository at this point in the history
Add support for reading TOML files via tomllib.
  • Loading branch information
dchukhin authored Aug 30, 2024
2 parents 4b32897 + a7f1ef4 commit 96b8c8f
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 7 deletions.
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
Change Log
==========

5.0.1 (Unreleased)
==================

- Support reading TOML files via ``tomllib`` on Python 3.11+

5.0.0 (13 August 2024)
========================

Expand Down
4 changes: 3 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ Installation

``pip install goodconf`` or ``pip install goodconf[yaml]`` /
``pip install goodconf[toml]`` if parsing/generating YAML/TOML
files is required.
files is required. When running on Python 3.11+ the ``[toml]``
extra is only required for generating TOML files as parsing
is supported natively.


Quick Start
Expand Down
12 changes: 9 additions & 3 deletions goodconf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,16 @@ def _load_config(path: str) -> dict[str, Any]:
yaml = ruamel.yaml.YAML(typ="safe", pure=True)
loader = yaml.load
elif ext == ".toml":
import tomlkit
try:
import tomllib

def load(stream):
return tomllib.loads(f.read())
except ImportError: # Fallback for Python < 3.11
import tomlkit

def load(stream):
return tomlkit.load(f).unwrap()
def load(stream):
return tomlkit.load(f).unwrap()

loader = load

Expand Down
8 changes: 5 additions & 3 deletions tests/test_file_helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os

import sys
import pytest

from goodconf import _find_file, _load_config
Expand All @@ -12,14 +12,16 @@ def test_json(tmpdir):


def test_load_toml(tmpdir):
pytest.importorskip("tomlkit")
if sys.version_info < (3, 11):
pytest.importorskip("tomlkit")
conf = tmpdir.join("conf.toml")
conf.write('a = "b"\nc = 3')
assert _load_config(str(conf)) == {"a": "b", "c": 3}


def test_load_empty_toml(tmpdir):
pytest.importorskip("tomlkit")
if sys.version_info < (3, 11):
pytest.importorskip("tomlkit")
conf = tmpdir.join("conf.toml")
conf.write("")
assert _load_config(str(conf)) == {}
Expand Down

0 comments on commit 96b8c8f

Please sign in to comment.