Skip to content

Commit

Permalink
Cast path segment to int if it's supposed to be an index
Browse files Browse the repository at this point in the history
  • Loading branch information
moomoohk committed Nov 29, 2022
1 parent 3a79ed0 commit 3e6565b
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 14 deletions.
14 changes: 2 additions & 12 deletions dpath/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
]

from collections.abc import MutableMapping, MutableSequence
from typing import Union, List, Any, Callable, Optional
from typing import Union, List, Any, Callable, Optional, Sequence

from dpath import segments, options
from dpath.exceptions import InvalidKeyName, PathNotFound
Expand All @@ -30,7 +30,7 @@
_DEFAULT_SENTINEL = object()


def _split_path(path: Path, separator: Optional[str]) -> Union[List[PathSegment], PathSegment]:
def _split_path(path: Path, separator: Optional[str] = "/") -> Union[List[PathSegment], PathSegment]:
"""
Given a path and separator, return a tuple of segments. If path is
already a non-leaf thing, return it.
Expand All @@ -45,16 +45,6 @@ def _split_path(path: Path, separator: Optional[str]) -> Union[List[PathSegment]
else:
split_segments = path.lstrip(separator).split(separator)

if options.CONVERT_INT_LIKE_SEGMENTS:
# Attempt to convert integer segments into actual integers.
final = []
for segment in split_segments:
try:
final.append(int(segment))
except ValueError:
final.append(segment)
split_segments = final

return split_segments


Expand Down
1 change: 0 additions & 1 deletion dpath/options.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
ALLOW_EMPTY_STRING_KEYS = False
CONVERT_INT_LIKE_SEGMENTS = True
5 changes: 5 additions & 0 deletions dpath/segments.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,11 @@ def set(
# For everything except the last value, walk down the path and
# create if creator is set.
for (i, segment) in enumerate(segments[:-1]):

# If segment is non-int but supposed to be a sequence index
if not isinstance(segment, int) and segment.isdigit() and isinstance(current, Sequence):
segment = int(segment)

try:
# Optimistically try to get the next value. This makes the
# code agnostic to whether current is a list or a dict.
Expand Down
2 changes: 1 addition & 1 deletion dpath/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ def creator(
segments: Sequence[PathSegment],
i: int,
hints: Sequence[Tuple[PathSegment, type]] = ()
)"""
) -> PathSegment"""

0 comments on commit 3e6565b

Please sign in to comment.