Issue #21481: Teach argparse equality tests to return NotImplemented when comparing to unknown types.
diff --git a/Lib/argparse.py b/Lib/argparse.py
index a4009d0..b5bb19a 100644
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -1157,9 +1157,13 @@
__hash__ = None
def __eq__(self, other):
+ if not isinstance(other, Namespace):
+ return NotImplemented
return vars(self) == vars(other)
def __ne__(self, other):
+ if not isinstance(other, Namespace):
+ return NotImplemented
return not (self == other)
def __contains__(self, key):
diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py
index fdf2b67..0df66ad 100644
--- a/Lib/test/test_argparse.py
+++ b/Lib/test/test_argparse.py
@@ -4453,6 +4453,12 @@
self.assertTrue(ns2 != ns3)
self.assertTrue(ns2 != ns4)
+ def test_equality_returns_notimplemeted(self):
+ # See issue 21481
+ ns = argparse.Namespace(a=1, b=2)
+ self.assertIs(ns.__eq__(None), NotImplemented)
+ self.assertIs(ns.__ne__(None), NotImplemented)
+
# ===================
# File encoding tests