__eq__ on a dict
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Mon Jul 11 07:48:11 EDT 2005
On Mon, 11 Jul 2005 12:42:55 +0200, Neil Benn wrote:
> Hello,
>
> I can't find the docs for __eq__ on a dict and I can't find
> a description on what the eq does (strangely it does implement > and <
> but I have no idea what that does). Does anyone know (definitively)
> what the __eq__, __gt__, __lt__ methods do.
>
> BTW, google is not my friend - I invited it out for a drink last
> week and it stood me up :-).
It works for me. Google on "__eq__ Python" and the 5th and 6th sites are:
http://python.active-venture.com/ref/customization.html
http://www.network-theory.co.uk/docs/pylang/ref_32.html
Normally, asking Python for help is a good way to read the docs, but in
this particular case, it is a big let-down:
py> help({}.__eq__)
Help on method-wrapper:
__eq__ = <method-wrapper object>
For any two objects x and y, when you call
x == y
Python calls x.__eq__(y). That includes dicts:
py> dictA = {0: "spam"}
py> dictB = {0: "sp" + "am"}
py> dictC = {1: "ham"}
py>
py> dictA == dictB
True
py> dictA.__eq__(dictB) # same as dictA == dictB
True
py> dictB == dictC # calls dictB.__eq__(dictC)
False
Two dicts are equal if they have the same keys and the same values.
In general, you should not call __eq__ directly, but use the == operator
instead.
Likewise:
x > y becomes x.__gt__(y)
x < y becomes x.__lt__(y)
x >= y becomes x.__ge__(y)
x <= y becomes x.__le__(y)
x != y becomes x.__ne__(y)
x <> y also becomes x.__ne__(y)
--
Steven
More information about the Python-list
mailing list