In general, I try very much to respect a modules privacy (If a variable is prefixed with an underscore, I don’t use it). I have a corner case, however, where it seems reasonably “safe”.
Here’s the demo ( my previous question )
parser=argparse.ArgumentParser()
parser.add_argument('--point',help='enter a point (e.g. 2,3,4)')
parser.parse_args('--point=-2,5,6'.split()) #works
parser.parse_args('--point -2,5,6'.split()) #doesn't work
This can be fixed by:
parser=argparse.ArgumentParser()
parser.add_argument('--point',help='enter a point (e.g. 2,3,4)')
parser.parse_args('--point=-2,5,6'.split()) #works
parser._negative_number_matcher = re.compile(r'^-\d+|^-\d*\.\d+')
#Next line works too on Cpython 2.6,
#got the idea from reading Cpython 3.2 source so it should work there too
parser.parse_args('--point -2,5,6'.split())
This amount of playing with the internals of a class seems OK in this instance because:
*If argparse changes that variable (unlikely) or a different python implementation does it differently, it seems very unlikely that this will change the behavior of the class causing something to break.
*other python implementations are likely to use cpython’s argparse since it is written in pure python (as far as I can tell).
*My code doesn’t depend critically on this “feature” working. (the user can always revert back to passing ‘–point=-2,5,6’)
My question is this: Am I missing something? Is this really a bad idea? Am I likely to break something? If it is, why?
I think it’s a bad idea, and not because it may break something in argparse internals, but because it’s just wrong.
^-\d+is not a valid regexp for negative numbers (since it matches-23foo), and having plain wrong things in code is not good for maintenance. Imagine yourself (or even worse someone else) staring at this code two years later and puzzling about how the heck^-\d+is supposed to match negative numbers!