Skip to content

key_wrap

Dynamically generate a wrapper class with rich comparison operators based on a key field.

This module provides the :func:key_wrap function which creates a new class that stores a designated key attribute and implements all standard comparison methods (lt, le, gt, ge, eq, ne) and hash based on that key. The generated class also includes a custom repr that displays the key value prominently.

Note that the generated comparison operators do not check the type of the other operand: comparing against an unrelated type raises AttributeError (or TypeError for hash-only operations) instead of returning NotImplemented.

Example
from py_misc_utils import key_wrap

PKey = key_wrap.key_wrap('PKey', 'id')
a = PKey(id=1, name='x')
b = PKey(id=1, name='y')

# Instances compare and hash by 'id' only.
assert a == b
assert a < PKey(id=2)
assert repr(a) == "id=[1] : {'name': 'x'}"

key_wrap(cname, key_name)

Generate a wrapper class that compares instances by a designated key attribute.

Parameters:

Name Type Description Default
cname

The name to give the generated class.

required
key_name

The attribute name used as the key for comparisons and hashing.

required

Returns:

Type Description

A newly created class whose instances compare by key_name and expose all

remaining kwargs as instance attributes.

Source code in py_misc_utils/key_wrap.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def key_wrap(cname, key_name):
  """Generate a wrapper class that compares instances by a designated key attribute.

  Args:
    cname: The name to give the generated class.
    key_name: The attribute name used as the key for comparisons and hashing.

  Returns:
    A newly created class whose instances compare by key_name and expose all
    remaining kwargs as instance attributes.
  """
  replaces = dict(CLASS=cname, KEY=key_name)

  results, = ut.compile(_KW_TEMPLATE, cname, vals=replaces)

  return results