473,795 Members | 2,854 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to deepcopy a slice object?

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\li b\copy.py", line 204, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "C:\Program Files\Python\li b\copy.py", line 336, in _reconstruct
y = callable(*args)
File "C:\Program Files\Python\li b\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.

Aug 15 '06 #1
7 2216
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.deepcop y( slice( 1, 10, 2 ) )
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Program Files\Python\li b\copy.py", line 204, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "C:\Program Files\Python\li b\copy.py", line 336, in _reconstruct
y = callable(*args)
File "C:\Program Files\Python\li b\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

Aug 15 '06 #2
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_parame ters
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_parame ters

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\li b\copy.py", line 204, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "C:\Program Files\Python\li b\copy.py", line 336, in _reconstruct
y = callable(*args)
File "C:\Program Files\Python\li b\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
Aug 15 '06 #3
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.

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.
Aug 15 '06 #4
Alexandre Guimond wrote:
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_parame ters
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_parame ters

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.deepcop y( slice( 1, 10, 2 ) )
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Program Files\Python\li b\copy.py", line 204, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "C:\Program Files\Python\li b\copy.py", line 336, in _reconstruct
y = callable(*args)
File "C:\Program Files\Python\li b\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
Ah, so you *do* want to deepcopy slice objects.. Neat. :-)

I can't do that, but I can show you a couple of ways to deepcopy
objects that have slices as attributes.

First, if the __init__() method and its args are sufficient to recreate
your objects then you could do something like this:

class DeepCopyable0:

def __init__(self, x, y, z, a, b, c):
self.slicex = slice(x, y, z)
self.slicey = slice(a, b, c)

def __deepcopy__(se lf, memo):

# Create local vars for brevity.
sx, sy = self.slicex, self.slicey

# Create a new DeepCopyable0 instance.
return DeepCopyable0(
sx.start, sx.stop, sx.step,
sy.start, sy.stop, sy.step
)

|>d0 = DeepCopyable0(1 , 2, 3, 4, 5, 6)
|>d0.slicex, d0.slicey
(slice(1, 2, 3), slice(4, 5, 6))
|>d1 = deepcopy(d0)
|>d1.slicex, d1.slicey
(slice(1, 2, 3), slice(4, 5, 6))

Otherwise, another way to do it would be to provide the pickling
protocol:

class DeepCopyable1:

def __init__(self, x, y, z, a, b, c):
# Pretend this was something more complicated.
self.slicex = slice(x, y, z)
self.slicey = slice(a, b, c)

def __getstate__(se lf):

state = self.__dict__.c opy()

# Create local vars for brevity.
sx, sy = self.slicex, self.slicey

# Save the indices rather than the slices.
state['slicex'] = sx.start, sx.stop, sx.step
state['slicey'] = sy.start, sy.stop, sy.step

return state

def __setstate__(se lf, state):

# Recreate the slice objects.
state['slicex'] = slice(*state['slicex'])
state['slicey'] = slice(*state['slicey'])

self.__dict__.u pdate(state)
|>d0 = DeepCopyable1(1 , 2, 3, 4, 5, 6)
|>d0.slicex, d0.slicey
(slice(1, 2, 3), slice(4, 5, 6))
|>d1 = deepcopy(d0)
|>d1.slicex, d1.slicey
(slice(1, 2, 3), slice(4, 5, 6))

Circular references seem work fine here too. Observe:

|>d0 = DeepCopyable1(1 , 2, 3, 4, 5, 6)
|>d0.rec = d0
|>d0
<delme.DeepCopy able instance at 0xb7d5cb2c>
|>d0.rec.rec #etc...
<delme.DeepCopy able instance at 0xb7d5cb2c>
|>d1 = deepcopy(d0)
|>d1
<delme.DeepCopy able instance at 0xb7d7878c>
|>d1.rec
<delme.DeepCopy able instance at 0xb7d7878c>

Since you're going to be using more dimensions, you could make python
do the work for you rather than cutting and pasting:

class DeepCopyable2:

# __init__() omitted...

def __getstate__(se lf):
state = self.__dict__.c opy()

# Keep track of the slice attributes
slices = state['slices'] = []

# Convert slices to indices.
for attr, s in state.items():
if isinstance(s, slice):
state[attr] = s.start, s.stop, s.step
slices.append(a ttr)

return state

def __setstate__(se lf, state):

slices = state.pop('slic es')

# Recreate the slice objects.
for attr in slices:
state[attr] = slice(*state[attr])

self.__dict__.u pdate(state)
(I copied over the __init__() method from DeepCopyable for this
example.)
|>from delme import *
|>d0 = DeepCopyable2(1 , 2, 3, 4, 5, 6)
|>d1 = deepcopy(d0)
|>d1.slicex, d1.slicey
(slice(1, 2, 3), slice(4, 5, 6))

HTH. :)

I haven't used numpy (yet) and I've never explicitly used slice
objects, so the idea of storing and copying them struck me funny. I
find it very interesting and amusing that someone somewhere has a use
for them like this.

Peace,
~Simon

Aug 15 '06 #5
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.BuiltinFu nctionType):
d[t] = _copy_immutable
and, lower down, around line 214, adding a line like this:

d[types.SliceType] = _deepcopy_atomi c
I think I'll send a patch in in awhile. ;-)

Peace,
~Simon

Aug 15 '06 #6
thx for all the help simon. good ideas i can work with.

thx again.

alex.

Simon Forman wrote:
Alexandre Guimond wrote:
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_parame ters
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_parame ters

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\li b\copy.py", line 204, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "C:\Program Files\Python\li b\copy.py", line 336, in _reconstruct
y = callable(*args)
File "C:\Program Files\Python\li b\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

Ah, so you *do* want to deepcopy slice objects.. Neat. :-)

I can't do that, but I can show you a couple of ways to deepcopy
objects that have slices as attributes.

First, if the __init__() method and its args are sufficient to recreate
your objects then you could do something like this:

class DeepCopyable0:

def __init__(self, x, y, z, a, b, c):
self.slicex = slice(x, y, z)
self.slicey = slice(a, b, c)

def __deepcopy__(se lf, memo):

# Create local vars for brevity.
sx, sy = self.slicex, self.slicey

# Create a new DeepCopyable0 instance.
return DeepCopyable0(
sx.start, sx.stop, sx.step,
sy.start, sy.stop, sy.step
)

|>d0 = DeepCopyable0(1 , 2, 3, 4, 5, 6)
|>d0.slicex, d0.slicey
(slice(1, 2, 3), slice(4, 5, 6))
|>d1 = deepcopy(d0)
|>d1.slicex, d1.slicey
(slice(1, 2, 3), slice(4, 5, 6))

Otherwise, another way to do it would be to provide the pickling
protocol:

class DeepCopyable1:

def __init__(self, x, y, z, a, b, c):
# Pretend this was something more complicated.
self.slicex = slice(x, y, z)
self.slicey = slice(a, b, c)

def __getstate__(se lf):

state = self.__dict__.c opy()

# Create local vars for brevity.
sx, sy = self.slicex, self.slicey

# Save the indices rather than the slices.
state['slicex'] = sx.start, sx.stop, sx.step
state['slicey'] = sy.start, sy.stop, sy.step

return state

def __setstate__(se lf, state):

# Recreate the slice objects.
state['slicex'] = slice(*state['slicex'])
state['slicey'] = slice(*state['slicey'])

self.__dict__.u pdate(state)
|>d0 = DeepCopyable1(1 , 2, 3, 4, 5, 6)
|>d0.slicex, d0.slicey
(slice(1, 2, 3), slice(4, 5, 6))
|>d1 = deepcopy(d0)
|>d1.slicex, d1.slicey
(slice(1, 2, 3), slice(4, 5, 6))

Circular references seem work fine here too. Observe:

|>d0 = DeepCopyable1(1 , 2, 3, 4, 5, 6)
|>d0.rec = d0
|>d0
<delme.DeepCopy able instance at 0xb7d5cb2c>
|>d0.rec.rec #etc...
<delme.DeepCopy able instance at 0xb7d5cb2c>
|>d1 = deepcopy(d0)
|>d1
<delme.DeepCopy able instance at 0xb7d7878c>
|>d1.rec
<delme.DeepCopy able instance at 0xb7d7878c>

Since you're going to be using more dimensions, you could make python
do the work for you rather than cutting and pasting:

class DeepCopyable2:

# __init__() omitted...

def __getstate__(se lf):
state = self.__dict__.c opy()

# Keep track of the slice attributes
slices = state['slices'] = []

# Convert slices to indices.
for attr, s in state.items():
if isinstance(s, slice):
state[attr] = s.start, s.stop, s.step
slices.append(a ttr)

return state

def __setstate__(se lf, state):

slices = state.pop('slic es')

# Recreate the slice objects.
for attr in slices:
state[attr] = slice(*state[attr])

self.__dict__.u pdate(state)
(I copied over the __init__() method from DeepCopyable for this
example.)
|>from delme import *
|>d0 = DeepCopyable2(1 , 2, 3, 4, 5, 6)
|>d1 = deepcopy(d0)
|>d1.slicex, d1.slicey
(slice(1, 2, 3), slice(4, 5, 6))

HTH. :)

I haven't used numpy (yet) and I've never explicitly used slice
objects, so the idea of storing and copying them struck me funny. I
find it very interesting and amusing that someone somewhere has a use
for them like this.

Peace,
~Simon
Aug 16 '06 #7
Alexandre Guimond wrote:
thx for all the help simon. good ideas i can work with.

thx again.

alex.
You're very welcome, a pleasure. ;-)

~Simon

Aug 16 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1506
by: Eugeni Doljenko | last post by:
There is a list of custom objects. I want do duplicate this list to modify objects in new list and then compare old and new. I could do it with deepcopy class foo: def __init__(self, str): self.str = str old = import copy
1
1885
by: OKB (not okblacke) | last post by:
I've noticed some peculiar behavior from copy.deepcopy: if you pass it a method or function object, it raises a TypeError somewhere in copy_reg saying "function() takes at least 2 arguments (0 given)". I'm guessing this is the constructor for functions, and it's somehow being incorrectly called, but I'm not really sure. This behavior is annoying, however. I realize the deepcopy documentation warns that it doesn't handle copying certain...
0
1337
by: Dan Perl | last post by:
Here is some code to illustrate a problem that I have: import copy class myc: def __init__(self): self.myf=file('bar.txt',"w") def foo(self): self.myf.write('hello world!') # it's going to fail for d.foo( ) c = myc()
7
3973
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 | last post by:
(see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2 arguments, got 0". Tested with Python 2.3.4 on OpenBSD and Python 2.4 on Win98; same results. Is this a bug in deepcopy, how I dynamically assign the instance method or something else? (See example code for how I did it.) If you're curious as...
6
3112
by: phil | last post by:
I posted the following yesterday and got no response and did some testing simplifying the circumstances and it appears that deepcopy fails when the object to be copied contains a reference to a Canvas Object. Perhaps any Tkinter object, didn't get that far. The problem arises because I have a geometry tutorial with a progression of drawings and want the students to be able to go "back". Creating "snapshots" of points in time in the...
0
1705
by: Joshua Ginsberg | last post by:
Howdy -- I have a class that has an attribute that is a dictionary that contains an object that has a kword argument that is a lambda. Confused yet? Simplified example: import copy class Foo: def __init__(self, fn=None):
3
5576
by: none | last post by:
I have a very complex data structure which is basically a class object containing (sometimes many) other class objects, function references, ints, floats, etc. The man for the copy module states pretty clearly that it will not copy methods or functions. I've looked around for a while (prob just using the wrong keywords) and haven't found a good solution. As a workaround I've been using cPickle, loads(dumps(obj)) which is incredibly slow...
0
1390
by: Robin Becker | last post by:
I'm using deepcopy in some code which eventually ends up by crash witht he following rather long winded error. I'm not directly using _hashlib.HASH, but I suppose something else along the way could be. Is there some nice way to make copy/deepcopy give more information when this error happens? I know what the top level object is, but presumably it's something further down that's causing the problem. .......... File...
1
2107
by: Wouter DW | last post by:
I read the article on http://www.python.org/download/releases/2.2/descrintro/#metaclasses and started using autoprop. But now I have a problem I can't seem to solve myself. class autoprop(type): def __init__(cls, name, bases, dict): super(autoprop, cls).__init__(name, bases, dict) props = {} for name in dict.keys(): if name.startswith("_get_") or name.startswith("_set_"):
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9522
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10448
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10217
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9046
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6784
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5566
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.