how to deepcopy a slice object?

Simon Forman rogue_pedro at yahoo.com
Tue Aug 15 18:06:07 EDT 2006


Duncan Booth wrote:
> Simon Forman wrote:
>
> > Why would you want to [deep]copy a slice object?
>
> I would guess the original poster actually wanted to copy a data structure
> which includes a slice object somewhere within it. That is a perfectly
> reasonable albeit somewhat unusual thing to want, however it doesn't work.

I figured it was either something like that or something really wacky.
:-)  Either way I was curious.

> Similarly in Python 2.4 you cannot deepcopy functions. That has been fixed
> in Python 2.5 but I guess nobody has tried deepcopying slices before so
> they haven't been fixed.

Shows how unusual it is.


Since slice objects appear to be immutable:

|>> s = slice(1)
|>> s
slice(None, 1, None)
|>> s.start = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'slice' object has only read-only attributes (assign to
.start)

etc...

fixing copy and deepcopy for slices would involve adding slice to the
tuple in this for statement in copy.py (starts on line 115 in my
version Python 2.4.3):

for t in (types.NoneType, int, long, float, bool, str, tuple,
          frozenset, type, xrange, types.ClassType,
          types.BuiltinFunctionType):
    d[t] = _copy_immutable


and, lower down, around line 214, adding a line like this:

d[types.SliceType] = _deepcopy_atomic


I think I'll send a patch in in awhile.  ;-)

Peace,
~Simon




More information about the Python-list mailing list