[Python-checkins] cpython: Issue #24360: Improve __repr__ of argparse.Namespace() for invalid identifiers.
berker.peksag
python-checkins at python.org
Wed Jul 29 22:51:53 CEST 2015
https://hg.python.org/cpython/rev/dcc00d9ba8db
changeset: 97136:dcc00d9ba8db
user: Berker Peksag <berker.peksag at gmail.com>
date: Wed Jul 29 23:51:47 2015 +0300
summary:
Issue #24360: Improve __repr__ of argparse.Namespace() for invalid identifiers.
Patch by Matthias Bussonnier.
files:
Lib/argparse.py | 8 +++++++-
Lib/test/test_argparse.py | 15 +++++++++++++++
Misc/NEWS | 3 +++
3 files changed, 25 insertions(+), 1 deletions(-)
diff --git a/Lib/argparse.py b/Lib/argparse.py
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -118,10 +118,16 @@
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
+ star_args = {}
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
- arg_strings.append('%s=%r' % (name, value))
+ if name.isidentifier():
+ arg_strings.append('%s=%r' % (name, value))
+ else:
+ star_args[name] = value
+ if star_args:
+ arg_strings.append('**%s' % repr(star_args))
return '%s(%s)' % (type_name, ', '.join(arg_strings))
def _get_kwargs(self):
diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py
--- a/Lib/test/test_argparse.py
+++ b/Lib/test/test_argparse.py
@@ -4512,6 +4512,21 @@
string = "Namespace(bar='spam', foo=42)"
self.assertStringEqual(ns, string)
+ def test_namespace_starkwargs_notidentifier(self):
+ ns = argparse.Namespace(**{'"': 'quote'})
+ string = """Namespace(**{'"': 'quote'})"""
+ self.assertStringEqual(ns, string)
+
+ def test_namespace_kwargs_and_starkwargs_notidentifier(self):
+ ns = argparse.Namespace(a=1, **{'"': 'quote'})
+ string = """Namespace(a=1, **{'"': 'quote'})"""
+ self.assertStringEqual(ns, string)
+
+ def test_namespace_starkwargs_identifier(self):
+ ns = argparse.Namespace(**{'valid': True})
+ string = "Namespace(valid=True)"
+ self.assertStringEqual(ns, string)
+
def test_parser(self):
parser = argparse.ArgumentParser(prog='PROG')
string = (
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,9 @@
Library
-------
+- Issue #24360: Improve __repr__ of argparse.Namespace() for invalid
+ identifiers. Patch by Matthias Bussonnier.
+
- Issue #23319: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch
written by Matthieu Gautier.
--
Repository URL: https://hg.python.org/cpython
More information about the Python-checkins
mailing list