Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-37150: Throw ValueError if FileType class object was passed in add_argument #13805

Merged
merged 2 commits into from
Jun 7, 2019
Merged
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
4 changes: 4 additions & 0 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1361,6 +1361,10 @@ def add_argument(self, *args, **kwargs):
if not callable(type_func):
raise ValueError('%r is not callable' % (type_func,))

if type_func is FileType:
raise ValueError('%r is a FileType class object, instance of it'
' must be passed' % (type_func,))

# raise an error if the metavar does not match the type
if hasattr(self, "_get_formatter"):
try:
Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1619,6 +1619,24 @@ def test_open_args(self):
m.assert_called_with('foo', *args)


class TestFileTypeMissingInitialization(TestCase):
"""
Test that add_argument throws an error if FileType class
object was passed instead of instance of FileType
"""

def test(self):
parser = argparse.ArgumentParser()
with self.assertRaises(ValueError) as cm:
parser.add_argument('-x', type=argparse.FileType)

self.assertEqual(
'%r is a FileType class object, instance of it must be passed'
% (argparse.FileType,),
str(cm.exception)
)


class TestTypeCallable(ParserTestCase):
"""Test some callables as option/argument types"""

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`argparse._ActionsContainer.add_argument` now throws error, if someone accidentally pass FileType class object instead of instance of FileType as `type` argument