How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

avi.e.gross at gmail.com avi.e.gross at gmail.com
Tue Jan 24 17:38:44 EST 2023


If I understood the issue, the problem is the unary minus at the start of the expression. 

So if you know the expression is in that argument, would it make sense to pad it in one of many ways that are otherwise harmless?

Could you put parens on both sides of "-4^2+5.3*abs(-2-1)/2":

"(-4^2+5.3*abs(-2-1)/2)"

Or perhaps place a zero in front as in the awkward case where it begins with a minus sign:

"0 -4^2+5.3*abs(-2-1)/2"

Some people suggest you ask the user to modify what they type in and such changes may work. Your program could also potentially diddle with argv and recognize it albeit as you allow calling a function like abs() I can easily imagine a potentially valid looking "-abs(...)..." that could look like -a followed by something.

I see a deeper issue with interactions at the command shell level if parts of the arithmetic expression are evaluated or changed before python is even invoked.

Then again, I may be misunderstanding the issue.



-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com at python.org> On Behalf Of Jach Feng
Sent: Tuesday, January 24, 2023 2:21 AM
To: python-list at python.org
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

cameron... at gmail.com 在 2023年1月24日 星期二下午2:05:33 [UTC+8] 的信中寫道:
> On 23Jan2023 17:58, Jach Feng <jf... at ms4.hinet.net> wrote: 
> >>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
> >usage: [-h] infix
> >: error: unrecognized arguments: -4.3+5
> This error doesn't look like "-4.3+5 looks like an option" but instead 
> "we don't expect any arguments after "infix".
> 
> Not personally a fan of argparse myself, but then I have my own 
> elaborate command line framework which generally uses getopt for the 
> option stuff.
> 
> Cheers,
> Cameron Simpson <c... at cskk.id.au>
Hmm, good to you. During experiments in these days, I had found argparse shows some strange/unstable behaviors in dealing with the leading '-' situation.
--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list