Skip to content

Commit dea46ec

Browse files
committed
Issue #21481: Teach argparse equality tests to return NotImplemented when comparing to unknown types.
1 parent dd5e53a commit dea46ec

3 files changed

Lines changed: 13 additions & 0 deletions

File tree

Lib/argparse.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,9 +1198,13 @@ def __init__(self, **kwargs):
11981198
setattr(self, name, kwargs[name])
11991199

12001200
def __eq__(self, other):
1201+
if not isinstance(other, Namespace):
1202+
return NotImplemented
12011203
return vars(self) == vars(other)
12021204

12031205
def __ne__(self, other):
1206+
if not isinstance(other, Namespace):
1207+
return NotImplemented
12041208
return not (self == other)
12051209

12061210
def __contains__(self, key):

Lib/test/test_argparse.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4551,6 +4551,12 @@ def test_equality(self):
45514551
self.assertTrue(ns2 != ns3)
45524552
self.assertTrue(ns2 != ns4)
45534553

4554+
def test_equality_returns_notimplemeted(self):
4555+
# See issue 21481
4556+
ns = argparse.Namespace(a=1, b=2)
4557+
self.assertIs(ns.__eq__(None), NotImplemented)
4558+
self.assertIs(ns.__ne__(None), NotImplemented)
4559+
45544560

45554561
# ===================
45564562
# File encoding tests

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ Library
2424
- Issue #14710: pkgutil.find_loader() no longer raises an exception when a
2525
module doesn't exist.
2626

27+
- Issue #21481: Argparse equality and inequality tests now return
28+
NotImplemented when comparing to an unknown type.
29+
2730
- Issue #8743: Fix interoperability between set objects and the
2831
collections.Set() abstract base class.
2932

0 commit comments

Comments
 (0)