diff --git a/Lib/argparse.py b/Lib/argparse.py --- 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 --- 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