Skip to content

Commit

Permalink
bpo-37150: Throw ValueError if FileType class object was passed in ad…
Browse files Browse the repository at this point in the history
…d_argument (GH-13805)

There is a possibility that someone (like me) accidentally will omit parentheses with `FileType` arguments after `FileType`, and parser will contain wrong file until someone will try to use it.

Example:
```python
parser = argparse.ArgumentParser()
parser.add_argument('-x', type=argparse.FileType)
```

https://bugs.python.org/issue37150
(cherry picked from commit 03d5831)

Co-authored-by: zygocephalus <grrrr@protonmail.com>
  • Loading branch information
miss-islington and 0x29a authored Jun 7, 2019
1 parent 6c9effa commit 606ac58
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
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

0 comments on commit 606ac58

Please sign in to comment.