Commit 061e095
authored
This effectively treats an integer `x` as if it were the string `"[x]"`, allowing
`Path(x)` and `x + Path(...) + x` in addition to current `Path(...)[x]`.
There are several possible implementation approaches, including a straightforward
`if isinstance(x, int): x = f"[{int(x)}]"` in `__new__`, `__add__` and `__radd__`,
then letting it parse as an actual string.
However, not only that approach is very inefficient, as it calls the parser and
tokenization for a known outcome, but also this was not the approach taken by
`__getitem__`, currently the only method that can be used as reference on how to
properly handle integers.
It is also important be consistent with the current _semantics_ of `Path(x)` and
`Path + x`, as they're different from `Path[x]` for strings and Paths, so do
not converge to using `Path[x]` for both. Even if for integers it ends up being
the same result, as integers can only be a single index, do not rely on that
and keep semantics distinct and consistent with the string code path.
So in `__new__`, instead of resorting to a `return cls()[x]` shortcut, we call the
same classmethod as str and Path do, `cls.from_accessors()`, passing the same
argument as __getitem__ uses: a tuple with a single element `ListIndex(index=x)`,
which is also, not coincidentally, the same result of parsing `"[x]"`.
As for `__add__`/`__radd__`, again we use the same semantics as used by str:
`Path(...) + x == Path(...)[Path(x)]`, and `x + Path(...) == Path(x)[Path(...)]`
And, as we just defined `Path(x)` for an integer x, we can simply extend the
`isinstance(x, str)` check to include `int`, without creating a new case, thus
enforcing consistent semantics.
1 parent 099f3fe commit 061e095
1 file changed
+7
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
36 | 36 | | |
37 | 37 | | |
38 | 38 | | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
39 | 43 | | |
40 | 44 | | |
41 | 45 | | |
| |||
48 | 52 | | |
49 | 53 | | |
50 | 54 | | |
51 | | - | |
| 55 | + | |
52 | 56 | | |
53 | 57 | | |
54 | 58 | | |
| |||
68 | 72 | | |
69 | 73 | | |
70 | 74 | | |
71 | | - | |
| 75 | + | |
72 | 76 | | |
73 | 77 | | |
74 | 78 | | |
75 | 79 | | |
76 | 80 | | |
77 | 81 | | |
78 | 82 | | |
79 | | - | |
| 83 | + | |
80 | 84 | | |
81 | 85 | | |
82 | 86 | | |
| |||
0 commit comments