sagemath / sage

Main repository of SageMath
https://www.sagemath.org
Other
1.41k stars 474 forks source link

trivial __copy__ and __deepcopy__ methods for Family and Set #32462

Open mkoeppe opened 3 years ago

mkoeppe commented 3 years ago

The constructors Family and Set are intended to construct an immutable Parent.

We equip the implementation classes with trivial __copy__ and __deepcopy__ methods that just return self.

Parents that subclass CachedRepresentation/UniqueRepresentation already have these methods, but the implementation classes of Family and Set do not.

Slightly tricky is the question how to deal with mutable elements. Set documents that:

    Sets with unhashable objects work, but with less functionality::

        sage: B = Set([QQ, [3, 1], 5])  # unhashable

Should a copy be made? Should it be documented that by creating the Set, a mutable element belongs to the set object in the sense of object ownership and it is an error to mutate it?

CC: @tscrim @nbruin

Component: refactoring

Issue created by migration from https://trac.sagemath.org/ticket/32462

tscrim commented 3 years ago
comment:1

Probably the easiest way to do this would be to have a finite, e.g., Set try to make a copy of each member. If it returns the same object each time, then return self. For an infinite Family, we are safe as members are created on demand each time

mkoeppe commented 3 years ago
comment:2

What you are describing is deepcopy semantics and is what I implemented for __deepcopy__ of immutable vectors and sequences in the branch of #13811

tscrim commented 3 years ago
comment:3

Ah, right. I think hashability would be a good guide for this. If hashable, then return self otherwise play it safe and return a copy.