I would like to give slice string as argument, see below
import argparse
def _parse_slice(s):
a = [int(e) if e.strip() else None for e in s.split(":")]
return slice(*a)
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('-s', type=_parse_slice)
args = p.parse_args()
print(args.s)
It works fine with positive index, e.g., -s 1:10, -s -5 (which gives rise to slice[None, -5, None]) is also fine, but errors out with negative index as first parameter, e.g., -5:
usage: slice-parse.py [-h] [-s S]
slice-parse.py: error: argument -s: expected one argument
How should I support negative index as first slice parameter?
Fortunately, argparse by default does understand the = token
$ python slice-parse.py -s=-5:
slice(-5, None, None)
The reason why -5 works directly as one might expect is due to argparse having implemented some heuristics, which are detailed in the linked documentation (basically -5 looks like a number, -5: does not).
This issue is caused essentially by argparse treating all - (by default) as flags. This can be redefined using prefix_chars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With