Skip to content
Closed
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
15 changes: 14 additions & 1 deletion Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1350,7 +1350,17 @@ def __eq__(self, other):
return vars(self) == vars(other)

def __contains__(self, key):
return key in self.__dict__
return key in self.__dict__ or key.replace('-', '_') in self.__dict__

def __getattr__(self, name):
# Compatibility for people doing getattr(args, 'foo-bar') instead of
Copy link
Member

Choose a reason for hiding this comment

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

But what about setattr(args, 'foo-bar') and delattr(args, 'foo-bar')?

# args.foo_bar. This might lead to some false positives, but this
# is unlikely.
try:
return self.__dict__[name.replace('-', '_')]
except KeyError:
msg = "'%s' object has no attribute '%s'"
raise AttributeError(msg % (type(self).__name__, name))


class _ActionsContainer(object):
Expand Down Expand Up @@ -1577,6 +1587,9 @@ def _get_positional_kwargs(self, dest, **kwargs):
if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
kwargs['required'] = True

# make dest attribute-accessible, 'foo-bar' -> 'foo_bar'
dest = dest.replace('-', '_')
Copy link
Member

Choose a reason for hiding this comment

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

It has a side effect of changing the default metavar.


# return the keyword arguments with no option strings
return dict(kwargs, dest=dest, option_strings=[])

Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1348,6 +1348,16 @@ class TestPositionalsNargsOptionalOneOrMore(ParserTestCase):
]


class TestPositionalDest(ParserTestCase):
"""Tests setting destination"""

argument_signatures = [Sig("foo-bar")]
failures = []
successes = [
("biz", NS(foo_bar="biz")),
]


class TestPositionalsChoicesString(ParserTestCase):
"""Test a set of single-character choices"""

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hyphens in positional arguments in argparse module are automatically replaced with underscores. Patch by Simon Law and Furkan Onder.
Copy link
Member

Choose a reason for hiding this comment

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

It should be in the Library section.