Skip to content

Commit

Permalink
Add optional encoding parameter to load and dump functions (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
Backist authored Jan 3, 2024
1 parent 85a132e commit 8c7b4c3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
3 changes: 1 addition & 2 deletions benchmark/run.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import timeit
from pathlib import Path

_parsers = []

import pytomlpp
_parsers.append(('pytomlpp', pytomlpp.loads))
_parsers = [('pytomlpp', pytomlpp.loads)]

try:
import rtoml
Expand Down
16 changes: 9 additions & 7 deletions src/pytomlpp/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,23 @@ def dumps(data: Dict[Any, Any]) -> str:
return _impl.dumps(data)


def dump(data: Dict[Any, Any], fl: FilePathOrObject, mode: str = "w", encoding: Optional[str] = "utf-8") -> None:
def dump(data: Dict[Any, Any], fl: FilePathOrObject, mode: str = "w", encoding: Optional[str] = None) -> None:
"""Serialise data to TOML file
Args:
data (Dict[Any, Any]): input data
fl (FilePathOrObject): file like object or path
mode (str, optional): mode to write the file, support "w", "wt" (text) or "wb" (binary). Defaults to "w".
encoding (str): defaults to utf-8, if None, local encoding is selected.
encoding (str): defaults to None. If None, local enconding will be selected.
NOTE: ``If mode is binary mode, encoding optional argument will be negligible.``
"""
data = _impl.dumps(data)
if mode == "wb":
data = data.encode("utf-8")
if hasattr(fl, "write"):
fl.write(data)
return
with open(fl, mode=mode, encoding=encoding or None) as fh:
with open(fl, mode=mode, encoding=encoding) as fh:
fh.write(data)


Expand All @@ -51,21 +52,22 @@ def loads(data: str) -> Dict[Any, Any]:
return _impl.loads(data)


def load(fl: FilePathOrObject, mode: str = "r", encoding: Optional[str] = "utf-8") -> Dict[Any, Any]:
def load(fl: FilePathOrObject, mode: str = "r", encoding: Optional[str] = None) -> Dict[Any, Any]:
"""Deserialise from TOML file to python dict.
Args:
fl (FilePathOrObject): file like object or path
mode (str, optional): mode to read the file, support "r", "rt" (text) or "rb" (binary). Defaults to "r".
encoding (str): defaults to None. If None, local enconding will be selected.
NOTE: ``If mode is binary mode, encoding optional argument will be negligible.``
Returns:
Dict[Any, Any]: deserialised data
"""

if hasattr(fl, "read"):
data = fl.read()
else:
with open(fl, mode=mode, encoding=encoding or None) as fh:
with open(fl, mode=mode, encoding=encoding) as fh:
data = fh.read()
if isinstance(data, bytes):
return _impl.loads(data.decode("utf-8"))
Expand Down

0 comments on commit 8c7b4c3

Please sign in to comment.