samuelcolvin / rtoml
1 3
from datetime import date, datetime, time, timezone
2 3
from io import TextIOBase
3 3
from pathlib import Path
4 3
from typing import Any, TextIO, Union
5

6 3
from . import _rtoml
7

8 3
__all__ = 'VERSION', 'TomlParsingError', 'TomlSerializationError', 'load', 'loads', 'dumps', 'dump'
9

10
# VERSION is set in Cargo.toml
11 3
VERSION = _rtoml.VERSION
12 3
TomlParsingError = _rtoml.TomlParsingError
13 3
TomlSerializationError = _rtoml.TomlSerializationError
14

15

16 3
def load(toml: Union[str, Path, TextIO]) -> Any:
17
    """
18
    Parse TOML via a string or file and return a python object. The `toml` argument may be a `str`,
19
    `Path` or file object from `open()`.
20
    """
21 3
    if isinstance(toml, Path):
22 3
        toml = toml.read_text()
23 3
    elif isinstance(toml, (TextIOBase, TextIO)):
24 3
        toml = toml.read()
25

26 3
    return loads(toml)
27

28

29 3
def loads(toml: str) -> Any:
30
    """
31
    Parse a TOML string and return a python object. (provided to match the interface of `json` and similar libraries)
32
    """
33 3
    if not isinstance(toml, str):
34 3
        raise TypeError(f'invalid toml input, must be str not {type(toml)}')
35 3
    return _rtoml.deserialize(toml, parse_datetime)
36

37

38 3
def dumps(obj: Any, *, pretty: bool = False) -> str:
39
    """
40
    Serialize a python object to TOML.
41

42
    If `pretty` is true, output has a more "pretty" format.
43
    """
44 3
    if pretty:
45 3
        serialize = _rtoml.serialize_pretty
46
    else:
47 3
        serialize = _rtoml.serialize
48

49 3
    return serialize(obj)
50

51

52 3
def dump(obj: Any, file: Union[Path, TextIO], *, pretty: bool = False) -> int:
53
    """
54
    Serialize a python object to TOML and write it to a file. `file` may be a `Path` or file object from `open()`.
55

56
    If `pretty` is true, output has a more "pretty" format.
57
    """
58 3
    s = dumps(obj, pretty=pretty)
59 3
    if isinstance(file, Path):
60 3
        return file.write_text(s)
61
    else:
62 3
        return file.write(s)
63

64

65 3
def parse_datetime(v: str) -> Union[date, time]:
66 3
    try:
67 3
        return date.fromisoformat(v)
68 3
    except ValueError:
69 3
        tz = None
70 3
        if v.endswith(('z', 'Z')):
71 3
            tz = timezone.utc
72 3
            v = v[:-1]
73 3
        try:
74 3
            dt = datetime.fromisoformat(v)
75 3
        except ValueError:
76 3
            return time.fromisoformat(v)
77
        else:
78 3
            if tz:
79 3
                dt = dt.replace(tzinfo=tz)
80 3
            return dt

Read our documentation on viewing source code .

Loading