Coverage for src/qollib/strings/np_shape_parser.py: 100%

18 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-02 08:34 +0000

1from typing import Union 

2 

3 

4def parse_shape(string: str) -> tuple: 

5 """ 

6 Parses a numpy like shape string, e.g. [0:,42:1337] 

7 :returns: a tuple of slices that can be used with numpy arrays 

8 """ 

9 string = string.strip("[]") 

10 return tuple(to_slice(d) if ':' in d else to_int(d) for d in string.split(",")) 

11 

12 

13def to_slice(string: str, delimiter: str = ':') -> slice: 

14 """:returns: a slice with start and stop taken from the string, seperated by delimiter, e.g. 3:7""" 

15 start, stop = string.split(delimiter) 

16 return slice(to_int(start), to_int(stop)) 

17 

18 

19def to_int(string: str) -> Union[int, None]: 

20 """:returns: an integer if the string is numeric""" 

21 if string.strip().isnumeric(): 

22 return int(string) 

23 return None 

24 

25 

26def shape_slices_to_string(shape: tuple) -> str: 

27 out = [] 

28 for dim in shape: 

29 if isinstance(dim, slice): 

30 out.append(f'{dim.start}:{dim.stop}') 

31 else: 

32 out.append(str(dim)) 

33 return f"[{', '.join(out)}]"