Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ def _copy_items(items):
return copy.copy(items)


def _identity(value):
return value


# ===============
# Formatting Help
# ===============
Expand Down Expand Up @@ -199,7 +203,7 @@ def _set_color(self, color, *, file=None):
self._decolor = decolor
else:
self._theme = get_theme(force_no_color=True).argparse
self._decolor = lambda text: text
self._decolor = _identity

# ===============================
# Section and indentation methods
Expand Down Expand Up @@ -1981,9 +1985,7 @@ def __init__(self,
self._subparsers = None

# register types
def identity(string):
return string
self.register('type', None, identity)
self.register('type', None, _identity)

# add help argument if necessary
# (using explicit default to override global argument_default)
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,25 @@ def test_skip_invalid_stdout(self):
self.assertRegex(mocked_stderr.getvalue(), r'usage:')


class TestArgumentParserPickleable(unittest.TestCase):

@force_not_colorized
def test_pickle_roundtrip(self):
import pickle
parser = argparse.ArgumentParser(exit_on_error=False)
parser.add_argument('--foo', type=int, default=42)
parser.add_argument('bar', nargs='?', default='baz')
# Try to pickle and unpickle the parser
parser2 = pickle.loads(pickle.dumps(parser))
# Check that the round-tripped parser still works
ns = parser2.parse_args(['--foo', '123', 'quux'])
self.assertEqual(ns.foo, 123)
self.assertEqual(ns.bar, 'quux')
ns2 = parser2.parse_args([])
self.assertEqual(ns2.foo, 42)
self.assertEqual(ns2.bar, 'baz')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to test all pickle protocols, as in test_uuid.BaseTestUUID.test_pickle_roundtrip? cc @savannahostrowski @serhiy-storchaka

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I can do that. Should I wait for a response from @savannahostrowski @serhiy-storchaka?



class TestCase(unittest.TestCase):

def setUp(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make sure that :class:`argparse.ArgumentParser` is pickleable.
Loading