Skip to content

Commit c16f7b0

Browse files
committed
Add warning on shallow copy of object with cached_method
1 parent 70f47a4 commit c16f7b0

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/sage/misc/cachefunc.pyx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,30 @@ the parent as its first argument::
406406
sage: d = a.add_bigoh(1) # needs sage.rings.padics
407407
sage: b._cache_key() == d._cache_key() # this would be True if the parents were not included
408408
False
409+
410+
Note that shallow copy of mutable objects may behave unexpectedly::
411+
412+
sage: class Foo:
413+
....: @cached_method
414+
....: def f(self):
415+
....: return self.x
416+
sage: from copy import copy, deepcopy
417+
sage: a = Foo()
418+
sage: a.x = 1
419+
sage: a.f()
420+
1
421+
sage: b = copy(a)
422+
sage: b.x = 2
423+
sage: b.f() # incorrect!
424+
1
425+
sage: b.f is a.f # this is the problem
426+
True
427+
sage: b = deepcopy(a)
428+
sage: b.x = 2
429+
sage: b.f() # correct
430+
2
431+
sage: b.f is a.f
432+
False
409433
"""
410434

411435
# ****************************************************************************

0 commit comments

Comments
 (0)