Welcome, guest | Sign In | My Account | Store | Cart

I would like to solve this excercise: Traditionally object-oriented programming provides two different modes for cloning an instance or a structured data type: shallow and deep copy. The former has the effect to clone exclusively the external shell and not its content originating a quite fastidious aliasing effect. The latter, instead, copies the shell and its content recursively creating two completely separate copies of the instance.

As you know, Python's programs suffer of the aliasing effect when you copy an instance of a class or a structured type (e.g., a list) with the = operator. As showed in the following example:

l=[0,1,2] mylist=l mylist[2] = ’B’ mylist [1, 2, ’B’] l [1, 2, ’B’

The exercise consists of defining a meta-class which implements the deep copy on the assignment operator and binding this to the standard class list. Such that the following behavior can be yielded

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
if __name__ == "__main__":
  mylist=list()
  mylist.append(0)
  mylist.append(1)
  mylist.append(2) 
  seclist=mylist
  seclist[2] = X
  seclist
  [0, 1, X]
  mylist
  [0, 1, 2]

3 comments

thonpy (author) 9 years, 9 months ago  # | flag

a possible solution is:

class metacl(type): def __new__(meta,classname,supers,classdict): #for attr in classdict.items(): classdict['__copy__'] = deepcopy #io ho messo la funz attraverso il classdict ma come la userà list? #classdict['__setslice__'] = funz #va sovrascritto il setitem credo
print("classname", classname)
return type.__new__(meta,classname,supers,classdict) def __setattr__(self, attr, value): # Outside accesses self.__slots__[attr] = deepcopy(value) # Avoid looping

class list(list,metaclass=metacl): pass

but i don't know what put in classdict!

beni hess 9 years, 9 months ago  # | flag

Python's programs suffer of the aliasing effect when you copy an instance of a class or a structured type (e.g., a list) with the = operator.

That's wrong, Python does not make a copy when you use the assign-operator, it just assigns the name to that object. If you change this behaviour, how do you assign a new name to an existing object?

Also i don't see why you mention shallow and deep copy and then the assign-operator, which neither makes a shallow nor a deep copy.

Your example doesn't make any copy, it just assigns the name seclist to the same object as mylist, it doesn't create any copy.

Your requested change breaks the language design and therefore if you want it you should use another language (in my opinion).

paolo 9 years, 9 months ago  # | flag

esami di programmazione avanzata ? :D

Created by thonpy on Sun, 26 Feb 2012 (MIT)
Python recipes (4591)
thonpy's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks