Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse negative index for slice object to argparse.ArgumentParser

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?

like image 567
nos Avatar asked Feb 18 '26 04:02

nos


1 Answers

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.

like image 194
metatoaster Avatar answered Feb 19 '26 18:02

metatoaster