homepage

This issue tracker has been migrated to GitHub , and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author invisibleroads
Recipients invisibleroads
Date 2015年04月28日.17:57:25
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1430243845.68.0.464856289952.issue24070@psf.upfronthosting.co.za>
In-reply-to
Content
Exceptions and arguments disappear when using argparse inside a "with" statement. The behavior was confusing and frustrating because I could not pinpoint why certain arguments were missing or unrecognized.
Unhandled exceptions inside the with statement typically trigger a traceback, unless __exit__ returns True, in which the exception is "swallowed" (https://www.python.org/dev/peps/pep-0343/).
However, the NameError exception and tile_indices argument disappear because of a premature sys.exit (https://hg.python.org/cpython/file/default/Lib/argparse.py#l2385).
```
"""
$ python exception-in-with.py
EXPECTED
Traceback (most recent call last):
 File "exception-in-with.py", line 51, in <module>
 abc # !!!
NameError: name 'abc' is not defined
ACTUAL
usage: exception-in-with.py [-h] --image_path PATH
exception-in-with.py: error: argument --image_path is required
$ python exception-in-with.py --image_path x
EXPECTED == ACTUAL
Traceback (most recent call last):
 File "exception-in-with.py", line 51, in <module>
 abc # !!!
NameError: name 'abc' is not defined
$ python exception-in-with.py --image_path x --tile_indices 1
EXPECTED
Traceback (most recent call last):
 File "exception-in-with.py", line 51, in <module>
 abc # !!!
NameError: name 'abc' is not defined
ACTUAL
usage: exception-in-with.py [-h] --image_path PATH
exception-in-with.py: error: unrecognized arguments: --tile_indices 1
"""
from argparse import ArgumentParser
class Starter(object):
 def __init__(self):
 self.argument_parser = ArgumentParser()
 def __enter__(self):
 return self
 def __exit__(self, exception_type, exception_value, exception_traceback):
 self.argument_parser.parse_args()
 def add_argument(self, *args, **kw):
 self.argument_parser.add_argument(*args, **kw)
with Starter() as starter:
 starter.add_argument('--image_path', metavar='PATH', required=True)
 abc # !!!
 starter.add_argument('--tile_indices', metavar='INTEGER')
```
History
Date User Action Args
2015年04月28日 17:57:25invisibleroadssetrecipients: + invisibleroads
2015年04月28日 17:57:25invisibleroadssetmessageid: <1430243845.68.0.464856289952.issue24070@psf.upfronthosting.co.za>
2015年04月28日 17:57:25invisibleroadslinkissue24070 messages
2015年04月28日 17:57:25invisibleroadscreate

AltStyle によって変換されたページ (->オリジナル) /