TOML support, closes #4

This commit is contained in:
Lucidiot 2019-09-22 19:54:46 +02:00
parent 2518e8a9aa
commit bfc64bb027
Signed by: lucidiot
GPG Key ID: 3358C1CA6906FB8D
3 changed files with 29 additions and 6 deletions

View File

@ -3,14 +3,13 @@ from collections.abc import Mapping, Iterable
from enum import Enum
from pathlib import Path
from objtools.registry import ClassRegistry
import json
import random
import yaml
class FileFormat(Enum):
JSON = 'json'
YAML = 'yaml'
TOML = 'toml'
class ComponentRegistry(ClassRegistry):
@ -60,11 +59,34 @@ class Component(metaclass=ComponentMetaclass, register=False):
if not isinstance(path, Path):
path = Path(path)
with path.open() as f:
method = json.load if fmt == FileFormat.JSON else yaml.safe_load
if fmt == FileFormat.JSON:
import json
data = json.load(f)
elif fmt == FileFormat.YAML:
try:
import yaml
except ImportError as e:
raise ImportError(
'{}\nYou may need to install madeleine with YAML support: '
'pip install madeleine[yaml]'.format(e.message),
)
data = yaml.safe_load(f)
elif fmt == FileFormat.TOML:
try:
import toml
except ImportError as e:
raise ImportError(
'{}\nYou may need to install madeleine with TOML support: '
'pip install madeleine[toml]'.format(e.message),
)
data = toml.load(f)
else:
raise NotImplementedError
if cls is Component:
# Guess the component type when calling Component.from_path
return Component._make(method(f))
return cls(**method(f))
return Component._make(data)
return cls(**data)
@staticmethod
def _make(data):

View File

@ -1,2 +1 @@
objtools>=0.1
pyyaml>=5.1

View File

@ -23,6 +23,8 @@ setup(
install_requires=requirements,
extras_require={
'dev': dev_requirements,
'yaml': ['pyyaml>=5.1'],
'toml': ['toml>=0.10'],
},
tests_require=dev_requirements,
test_suite='tests',