[firedrake] A note about Python objects

Martin Sandve Alnæs martinal at simula.no
Wed Jul 23 09:05:49 BST 2014


In UFL code contributed from the Firedrake team, there are some comments
I'd like to address:

The __eq__ operator of any Python object is used to compare for equality in
set and dict if __hash__ compares equal.

The __lt__ operator is used to define sorting, e.g. sorted(myobjects) will
use this operator.

Together these operators allow e.g. sorted(set(myobjects)) to get a sorted
unique list. It's not necessarily important for the sorting to have any
meaning, however it is important that it is deterministic between runs and
platforms.

Raising custom exceptions (including calling error()) in a Python special
function is always a bug. The correct behaviour is to "return
NotImplemented", which allows Python to follow its regular protocols. E.g.
when writing A < B, if A.__lt__(B) returns NotImplemented, Python will try
B.__lt__(A).

If any of this was news and you're writing significant Python code, I
recommend reading more here:
https://docs.python.org/2/reference/datamodel.html

Martin
-------------- next part --------------
HTML attachment scrubbed and removed


More information about the firedrake mailing list