how to deepcopy a slice object?

Alexandre Guimond alexandre.guimond at siemens.com
Tue Aug 15 05:57:40 EDT 2006


Here is my reason:

I have an object that contrains a 2D regular grid (matrix). In this
regular grid, I place points at regular intervals. In essence, i have
something like (my code is obviously more complex, this is just to show
what I want to do)

obj.grid = numpy.zeros( ( 100, 100 ) )
obj.grid[ obj.y1: obj.y2 : obj.ys, obj.x1 : obj.x2 : obj.xs ] =
embedded_parameters
result = somefunc( obj.grid )

My goal was to reduce the number of elements in my obj object by
replacing y1, y2, ys, and x1, x2, xs by 2 slice objects, and then do:

obj.grid[ obj.slicey, obj.slicex ] = embedded_parameters

But when I do this and then try to deepcopy my object, it doesn't work,
as in the example below.

Its not a big thing. I just liked the idea of having less elements in
my obj class and actually modeling my slice concept by a slice object,
specially since i'm going to 3D and 4D grid, and its somewhat annoying
to carry so many indices in my class definition.

Simon Forman wrote:
> Alexandre Guimond wrote:
> > Hi all,
> >
> > i'm trying to deepcopy a slice object but i get the following error.
> > Does anyone know a workaround?
> >
> > ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on
> > Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)]
> > on win32
> > Type "help", "copyright", "credits" or "license" for more information.
> > >>> import copy
> > >>> copy.deepcopy( slice( 1, 10, 2 ) )
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> >   File "C:\Program Files\Python\lib\copy.py", line 204, in deepcopy
> >     y = _reconstruct(x, rv, 1, memo)
> >   File "C:\Program Files\Python\lib\copy.py", line 336, in _reconstruct
> >     y = callable(*args)
> >   File "C:\Program Files\Python\lib\copy_reg.py", line 92, in
> > __newobj__
> >     return cls.__new__(cls, *args)
> > TypeError: slice expected at least 1 arguments, got 0
> >
> > thx for any help.
>
> Why would you want to [deep]copy a slice object?
>
> Anyway,  I don't know much about them, other than that they are
> slightly unusual objects that play a very restricted role in python,
> rather like the Ellipsis.
>
> Workarounds are possible, I think, but really you almost certainly
> don't need to do this.
> 
> Peace,
> ~Simon




More information about the Python-list mailing list