Skip to content

Commit f178642

Browse files
committed
Fixes #88
1 parent bade2c4 commit f178642

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

docs/slicing.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Slicing And Slices
2+
3+
4+
The way Python implements slicing is via overloading the `get-item` function call.
5+
This is the call the Python interpreter makes under the covers whenever you use the
6+
square bracket `[]` syntax.
7+
8+
9+
For quite a few objects, that function call take a tuple of arguments. The trick to
10+
numpy slicing is to create builtin slice objects with the appropriate arguments and
11+
pass them into the `get-item` call in a tuple.
12+
13+
14+
```clojure
15+
user> (require '[libpython-clj.python :as py])
16+
nil
17+
user> (require '[libpython-clj.require :refer [require-python]])
18+
... lotta logs ...
19+
user> (require-python '[builtins])
20+
WARNING: AssertionError already refers to: class java.lang.AssertionError in namespace: builtins, being replaced by: #'builtins/AssertionError
21+
WARNING: Exception already refers to: class java.lang.Exception in namespace: builtins, being replaced by: #'builtins/Exception
22+
:ok
23+
user> (doc builtins/slice)
24+
-------------------------
25+
builtins/slice
26+
[[self & [args {:as kwargs}]]]
27+
slice(stop)
28+
slice(start, stop[, step])
29+
30+
Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
31+
nil
32+
user> (require-python '[numpy :as np])
33+
:ok
34+
35+
user> (require-python '[numpy :as np])
36+
:ok
37+
user> (def ary (-> (np/arange 9)
38+
(np/reshape [3 3])))
39+
#'user/ary
40+
user> ary
41+
[[0 1 2]
42+
[3 4 5]
43+
[6 7 8]]
44+
45+
user> (py/get-item ary [(builtins/slice 1 nil) (builtins/slice 1 nil)])
46+
[[4 5]
47+
[7 8]]
48+
user> (py/get-item ary [(builtins/slice -1) (builtins/slice 1 nil)])
49+
[[1 2]
50+
[4 5]]
51+
user> (py/get-item ary [(builtins/slice nil) (builtins/slice 1 nil)])
52+
[[1 2]
53+
[4 5]
54+
[7 8]]
55+
user> (py/get-item ary [(builtins/slice nil) (builtins/slice 1 2)])
56+
[[1]
57+
[4]
58+
[7]]
59+
user> (py/get-item ary [(builtins/slice nil) (builtins/slice 1 3)])
60+
[[1 2]
61+
[4 5]
62+
[7 8]]
63+
user> (py/get-item ary [(builtins/slice nil) (builtins/slice 1 4)])
64+
[[1 2]
65+
[4 5]
66+
[7 8]]
67+
```

0 commit comments

Comments
 (0)