nti.schema.eqhash

Helpers for hashing and equality based on a list of names.

EqHash(*names, include_super=False, superhash=False, include_type=False)[source]

A class decorator factory for the common pattern of writing __eq__/__ne__ and __hash__ methods that check the same list of attributes on a given object.

Right now, you must pass as individual arguments the property names to check; in the future, you may be able to pass a schema interface that defines the property names. Property names are compared for equality in the order they are given, so place the cheapest first.

Additional parameters are only available via keywords:

>>> @EqHash('a', 'b')
... class Thing(object):
...   a = 1
...   b = 2
>>> hash(Thing()) == (hash(('a', 'b')) ^ hash((1, 2)))
True

>>> @EqHash('c', include_super=True)
... class ChildThing(Thing):
...   c = 3
>>> hash(ChildThing()) != hash(Thing()) != 0
True
Parameters:
  • include_super – If set to True (not the default) then the equality (and perhaps hash) values of super will be considered.
  • superhash – If set to True (not the default), then the hash function will be made to support certain mutable types (lists and dictionaries) that ordinarily cannot be hashed. Use this only when those items are functionally treated as immutable.
  • include_type – If set to True (not the default), equality will only be true if the other object is an instance of the class this is declared on. Use this only when there are a series of subclasses who differ in no attributes but should not compare equal to each other. Note that this can lead to violating the commutative property.