nti.schema.eqhash¶
Helpers for hashing and equality based on a list of names.
- EqHash(*names, include_super=False, superhash=False, supereq=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 >>> @EqHash('d', supereq=True) ... class Thing2: ... def __init__(self, d): self.d = d >>> Thing2([]) == Thing2(()) True >>> Thing2(set()) == Thing2(frozenset()) 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.supereq (bool) – If set to
True(not the default), then the equality method will treat lists and tuples as being equal. This is useful, for example, when you have a class default that’s an immutable tuple, but instances might have their own list value (containing the same data)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.
Changed in version 1.20.0: Add supereq to the equality operator for comparing mutable and immutable objects (tuple/list).