Skip to content

Commit

Permalink
Add weakref support for Basic's
Browse files Browse the repository at this point in the history
This fixes sympy/sympy#8825:

    >>> import weakref
    >>> import sympy
    >>> x, y = sympy.Symbol('x'), sympy.Symbol('y')
    >>> d = weakref.WeakKeyDictionary([(x, 1), (y, 2)])
    >>> print(list(d.items()))
    [(y, 2), (x, 1)]
    >>> del x
    >>> print(list(d.items()))
    [(y, 2)]

Cache now uses WeakValueDictionary.
  • Loading branch information
skirpichev committed Jan 25, 2016
1 parent 54e1502 commit 4175fad
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 4 deletions.
3 changes: 2 additions & 1 deletion sympy/core/basic.py
Expand Up @@ -41,7 +41,8 @@ class Basic(metaclass=ManagedProperties):
"""
__slots__ = ['_mhash', # hash value
'_args', # arguments
'_assumptions'
'_assumptions',
'__weakref__'
]

# To be overridden with True in the appropriate subclasses
Expand Down
3 changes: 2 additions & 1 deletion sympy/core/cache.py
@@ -1,6 +1,7 @@
""" Caching facility for SymPy """

from decorator import decorator
import weakref


# TODO: refactor CACHE & friends into class?
Expand Down Expand Up @@ -81,7 +82,7 @@ def __cacheit(f):
set environment variable SYMPY_USE_CACHE to 'debug'.
"""

func_cache_it_cache = {}
f._cache_it_cache = func_cache_it_cache = weakref.WeakValueDictionary()
CACHE.append((f, func_cache_it_cache))

def wrapper(f, *args, **kw_args):
Expand Down
14 changes: 13 additions & 1 deletion sympy/core/tests/test_symbol.py
@@ -1,8 +1,11 @@
import gc
import weakref

import pytest

from sympy import (Symbol, Wild, GreaterThan, LessThan, StrictGreaterThan,
StrictLessThan, pi, I, Rational, sympify, symbols, Dummy,
Integer, Float, sstr)
Integer, Float, sstr, default_sort_key)


def test_Symbol():
Expand Down Expand Up @@ -332,3 +335,12 @@ def test_call():
f = Symbol('f')
assert f(2)
pytest.raises(TypeError, lambda: Wild('x')(1))


def test_weakref():
x, y = Symbol('x'), Symbol('y')
d = weakref.WeakKeyDictionary([(x, 1), (y, 2)])
assert sstr(sorted(d.keys(), key=default_sort_key)) == '[x, y]'
del x
gc.collect()
assert sstr(list(d.keys())) == '[y]'
2 changes: 1 addition & 1 deletion sympy/utilities/tests/test_pickling.py
Expand Up @@ -24,7 +24,7 @@

from sympy import symbols, S

excluded_attrs = {'_assumptions', '_mhash'}
excluded_attrs = {'_assumptions', '_mhash', '__weakref__'}


def check(a, exclude=[], check_attr=True):
Expand Down

0 comments on commit 4175fad

Please sign in to comment.