On Thu, 22 Dec 2022 at 04:52, S.Y. Lee <[email protected]> wrote:
>
> Hashcons looks interesting, but as simple as making every object as singletons
> I would have a question how this would be implemented effectively on top of 
> python, for example, how to keep the hash table not grow infinitely with dead 
> references.

You would use weakref:
https://docs.python.org/3/library/weakref.html#weakref.WeakValueDictionary

I will write some blog posts about this in the new year but here's a
simple demo:

import weakref

_all_expressions = weakref.WeakValueDictionary()

class Expr:
    def __new__(cls, *args):
        expr = _all_expressions.get(args, None)
        if expr is not None:
            return expr
        expr = super().__new__(cls)
        _all_expressions[args] = expr
        return expr
    def __init__(self, *args):
        self.args = tuple(args)
    def __repr__(self):
        return f'{self.args[0]}{self.args[1:]}'

class Head:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name
    def __call__(*args):
        return Expr(*args)

Add = Head('Add')
Mul = Head('Mul')

print('empty:', dict(_all_expressions))
# empty: {}

expr = Add(1, Mul(2, 3))

print('not empty:', dict(_all_expressions))
# not empty: {(Mul, 2, 3): Mul(2, 3), (Add, 1, Mul(2, 3)): Add(1, Mul(2, 3))}

del expr  # clears the weakref dict

print('empty again:', dict(_all_expressions))
# empty again: {}

--
Oscar

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sympy/CAHVvXxSMt7Cxjk7f5-Fm1PmJCAcHSFT82%3DKE403JRmtxf5LPsg%40mail.gmail.com.

Reply via email to