Skip to content

Commit 3e6565b

Browse files
committed
Cast path segment to int if it's supposed to be an index
1 parent 3a79ed0 commit 3e6565b

4 files changed

Lines changed: 8 additions & 14 deletions

File tree

dpath/__init__.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
]
2222

2323
from collections.abc import MutableMapping, MutableSequence
24-
from typing import Union, List, Any, Callable, Optional
24+
from typing import Union, List, Any, Callable, Optional, Sequence
2525

2626
from dpath import segments, options
2727
from dpath.exceptions import InvalidKeyName, PathNotFound
@@ -30,7 +30,7 @@
3030
_DEFAULT_SENTINEL = object()
3131

3232

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

48-
if options.CONVERT_INT_LIKE_SEGMENTS:
49-
# Attempt to convert integer segments into actual integers.
50-
final = []
51-
for segment in split_segments:
52-
try:
53-
final.append(int(segment))
54-
except ValueError:
55-
final.append(segment)
56-
split_segments = final
57-
5848
return split_segments
5949

6050

dpath/options.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
ALLOW_EMPTY_STRING_KEYS = False
2-
CONVERT_INT_LIKE_SEGMENTS = True

dpath/segments.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,11 @@ def set(
320320
# For everything except the last value, walk down the path and
321321
# create if creator is set.
322322
for (i, segment) in enumerate(segments[:-1]):
323+
324+
# If segment is non-int but supposed to be a sequence index
325+
if not isinstance(segment, int) and segment.isdigit() and isinstance(current, Sequence):
326+
segment = int(segment)
327+
323328
try:
324329
# Optimistically try to get the next value. This makes the
325330
# code agnostic to whether current is a list or a dict.

dpath/types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,4 @@ def creator(
4242
segments: Sequence[PathSegment],
4343
i: int,
4444
hints: Sequence[Tuple[PathSegment, type]] = ()
45-
)"""
45+
) -> PathSegment"""

0 commit comments

Comments
 (0)