Skip to content

Commit 606ac58

Browse files
bpo-37150: Throw ValueError if FileType class object was passed in add_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 <[email protected]>
1 parent 6c9effa commit 606ac58

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

Lib/argparse.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1361,6 +1361,10 @@ def add_argument(self, *args, **kwargs):
13611361
if not callable(type_func):
13621362
raise ValueError('%r is not callable' % (type_func,))
13631363

1364+
if type_func is FileType:
1365+
raise ValueError('%r is a FileType class object, instance of it'
1366+
' must be passed' % (type_func,))
1367+
13641368
# raise an error if the metavar does not match the type
13651369
if hasattr(self, "_get_formatter"):
13661370
try:

Lib/test/test_argparse.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1619,6 +1619,24 @@ def test_open_args(self):
16191619
m.assert_called_with('foo', *args)
16201620

16211621

1622+
class TestFileTypeMissingInitialization(TestCase):
1623+
"""
1624+
Test that add_argument throws an error if FileType class
1625+
object was passed instead of instance of FileType
1626+
"""
1627+
1628+
def test(self):
1629+
parser = argparse.ArgumentParser()
1630+
with self.assertRaises(ValueError) as cm:
1631+
parser.add_argument('-x', type=argparse.FileType)
1632+
1633+
self.assertEqual(
1634+
'%r is a FileType class object, instance of it must be passed'
1635+
% (argparse.FileType,),
1636+
str(cm.exception)
1637+
)
1638+
1639+
16221640
class TestTypeCallable(ParserTestCase):
16231641
"""Test some callables as option/argument types"""
16241642

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
`argparse._ActionsContainer.add_argument` now throws error, if someone accidentally pass FileType class object instead of instance of FileType as `type` argument

0 commit comments

Comments
 (0)