Skip to content

Commit

Permalink
Add support for pathlib.Path. #144
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiocaccamo committed Jan 2, 2023
1 parent 1284afb commit a83e647
Show file tree
Hide file tree
Showing 8 changed files with 44 additions and 7 deletions.
12 changes: 7 additions & 5 deletions benedict/dicts/io/io_dict.py
Expand Up @@ -8,12 +8,14 @@ def __init__(self, *args, **kwargs):
"""
Constructs a new instance.
"""
# if first argument is data-string, url or filepath try to decode it.
# if first argument is data-string, url or filepath (str or pathlib.Path) try to decode it.
# use 'format' kwarg to specify the decoder to use, default 'json'.
if len(args) == 1 and type_util.is_string(args[0]):
d = IODict._decode_init(args[0], **kwargs)
super().__init__(d)
return
if len(args) == 1:
arg = args[0]
if type_util.is_string(arg) or type_util.is_path(arg):
d = IODict._decode_init(arg, **kwargs)
super().__init__(d)
return
super().__init__(*args, **kwargs)

@staticmethod
Expand Down
3 changes: 3 additions & 0 deletions benedict/dicts/io/io_util.py
Expand Up @@ -10,12 +10,14 @@


def autodetect_format(s):
s = str(s)
if any([is_url(s), is_s3(s), is_filepath(s)]):
return get_format_by_path(s)
return None


def decode(s, format, **kwargs):
s = str(s)
serializer = get_serializer_by_format(format)
if not serializer:
raise ValueError(f"Invalid format: {format}.")
Expand All @@ -34,6 +36,7 @@ def encode(d, format, filepath=None, **kwargs):
options = kwargs.copy()
content = serializer.encode(d, **options)
if filepath:
filepath = str(filepath)
write_content(filepath, content, **options)
return content

Expand Down
1 change: 1 addition & 0 deletions benedict/serializers/__init__.py
Expand Up @@ -65,6 +65,7 @@


def get_format_by_path(path):
path = str(path)
path = path.lower()
for extension in _SERIALIZERS_EXTENSIONS:
if path.endswith(extension):
Expand Down
5 changes: 5 additions & 0 deletions benedict/utils/type_util.py
@@ -1,3 +1,4 @@
import pathlib
import re
from datetime import datetime
from decimal import Decimal
Expand Down Expand Up @@ -70,6 +71,10 @@ def is_not_none(val):
return val is not None


def is_path(val):
return isinstance(val, pathlib.Path)


def is_regex(val):
return isinstance(val, regex)

Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Expand Up @@ -4,7 +4,7 @@ mailchecker == 5.0.5
openpyxl == 3.0.10
phonenumbers == 8.13.3
python-dateutil == 2.8.2
python-fsutil == 0.8.0
python-fsutil == 0.9.0
python-slugify == 7.0.0
pyyaml == 6.0
requests == 2.28.1
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Expand Up @@ -99,7 +99,7 @@ install_requires =
openpyxl >= 3.0.0, < 4.0.0
phonenumbers >= 8.12.0, < 9.0.0
python-dateutil >= 2.8.0, < 3.0.0
python-fsutil >= 0.6.0, < 1.0.0
python-fsutil >= 0.9.0, < 1.0.0
python-slugify >= 6.0.1, < 8.0.0
pyyaml >= 6.0, < 7.0
requests >= 2.26.0, < 3.0.0
Expand Down
1 change: 1 addition & 0 deletions tests/github/test_issue_0144.json
@@ -0,0 +1 @@
{"a": 1, "b": 2, "c": 3, "x": 7, "y": 8, "z": 9}
25 changes: 25 additions & 0 deletions tests/github/test_issue_0144.py
@@ -0,0 +1,25 @@
import pathlib
import unittest

from benedict import benedict


class github_issue_0144_test_case(unittest.TestCase):
"""
This class describes a github issue 0144 test case.
https://github.com/fabiocaccamo/python-benedict/issues/144
To run this specific test:
- Run python -m unittest tests.github.test_issue_0144
"""

def test_init_with_pathlib_path_object_and_valid_path(self):
# print(pathlib.Path("./test_issue_0144.json"))
d = benedict(pathlib.Path("tests/github/test_issue_0144.json"), format="json")
self.assertEqual(d, {"a": 1, "b": 2, "c": 3, "x": 7, "y": 8, "z": 9})

def test_init_with_pathlib_path_object_and_invalid_path(self):
with self.assertRaises(ValueError):
benedict(
pathlib.Path("tests/github/test_issue_0144_invalid.json"), format="json"
)

0 comments on commit a83e647

Please sign in to comment.