Simple class, that simplify usage of slices in __getitem__
Project description
slice-match
Simple class, that simplify usage of slices in __getitem__
.
Requirements
Python 3.10 and newer
Description
It's just a little trick, that allows you to do:
class custom_indexed:
def __getitem__(self, index):
match index:
case int(s):
print('this is "me[0]"-like expression')
case Slice(int(s)):
print('this is "me[0:]"-like expression')
case Slice(int(start), int(stop)):
print('this is "me[0:5]"-like expression')
case Slice(int(start), int(stop), int(stride)):
print('this is "me[0:5:2]"-like expression')
case Slice(start, None, stride):
print('this is "me[<Any>::<Any>]"-like expression')
Performance drop
For testing purpose, special class created:
class gg:
def __class_getitem__(cls, index):
return index
Tested constructions:
%%timeit
match gg[:12]:
case slice() as x if x.start is None and isinstance((y := x.stop), int) and x.step is None:
i = y
case _:
i = -1
Result:
740 ns ± 83 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
%%timeit
match gg[:12]:
case slice() as x:
match x.start, x.stop, x.step:
case None, int(y), None:
i = y
case _:
i = -1
Result:
2.02 µs ± 251 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
%%timeit
match gg[:14]:
case Slice(None, int(y), None):
i = y
case _:
i = -1
Result:
3.33 µs ± 436 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
So, readability improved (over 9000% ;) ), but performance slightly drops (+2.5 µs for each Slice in match-case)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
slice-match-0.1.0.tar.gz
(2.9 kB
view hashes)
Built Distribution
Close
Hashes for slice_match-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9f6841444154890b9d4eec0743cea44603bc42c2ad4f8b64ea178691c87821a8 |
|
MD5 | f8cb3f0d3225907941b8b57211cb2a15 |
|
BLAKE2b-256 | aa0300dba9719db03456d681d9f2ef3e8c4b62c30041443781ffdca8b1686543 |