Skip to content

hashcons

HashCons

Source code in src/finch/symbolic/hashcons.py
class HashCons:
    def __new__(cls, *args: Any) -> Self:
        hash_key = cls.hash_key(*args)
        if (cached := _table.get(hash_key)) is not None:
            return cached
        ret = super().__new__(cls)
        _table[hash_key] = ret
        return ret

    __eq__ = object.__eq__
    __hash__ = object.__hash__

    def __copy__(self) -> Self:
        return self

    def __deepcopy__(self, memo: dict) -> Self:
        return self

    @staticmethod
    def canonicalize(a: T, /) -> tuple[type[T], Hashable]:
        """
        Canonicalize an instance of this class into a (type, hashable) pair.

        Generic version provided, but one can override for speed.
        """
        if isinstance(a, numbers.Real):
            return type(a), _nan_to_none(float(a))

        if isinstance(a, numbers.Complex):
            return type(a), (_nan_to_none(float(a.real)), _nan_to_none(float(a.imag)))

        if isinstance(a, Hashable):
            return type(a), a

        return type(a), id(a)

    @classmethod
    def hash_key(cls, *args: Any) -> tuple[Hashable, ...]:
        """
        The hash key for this class, when it is constructed with `*args`.

        Generic version provided, but one can specialize for speed.
        """
        return (cls, *(cls.canonicalize(a) for a in args))

canonicalize(a) staticmethod

Canonicalize an instance of this class into a (type, hashable) pair.

Generic version provided, but one can override for speed.

Source code in src/finch/symbolic/hashcons.py
@staticmethod
def canonicalize(a: T, /) -> tuple[type[T], Hashable]:
    """
    Canonicalize an instance of this class into a (type, hashable) pair.

    Generic version provided, but one can override for speed.
    """
    if isinstance(a, numbers.Real):
        return type(a), _nan_to_none(float(a))

    if isinstance(a, numbers.Complex):
        return type(a), (_nan_to_none(float(a.real)), _nan_to_none(float(a.imag)))

    if isinstance(a, Hashable):
        return type(a), a

    return type(a), id(a)

hash_key(*args) classmethod

The hash key for this class, when it is constructed with *args.

Generic version provided, but one can specialize for speed.

Source code in src/finch/symbolic/hashcons.py
@classmethod
def hash_key(cls, *args: Any) -> tuple[Hashable, ...]:
    """
    The hash key for this class, when it is constructed with `*args`.

    Generic version provided, but one can specialize for speed.
    """
    return (cls, *(cls.canonicalize(a) for a in args))