Python deepcopy list at assignment

Got this exercise in python exam. Trying to return a deep copy of this list:

l = list() l = [0,1,2] l1 = l l[0] = 1 

l1 must contain [0,1,2] not [1,1,2]

The exercise indicated for its implementation using the metaclass.

 class deep(type): def __new__(meta, classname, bases, classDict): return type.__new__(meta, classname, bases, classDict) def __init__(cls, name, bases, dct): super(deep, cls).__init__(name, bases, dct) def __call__(cls, *args, **kwds): return type.__call__(cls, *args, **kwds) class list(metaclass=deep): def __init__(self): pass 

From what I know, '=' in python is an operator, not an operator, and cannot be overridden. Any idea on how to return a deep copy on appointment? We tried quite a lot, but without success.

+6
source share
2 answers

As far as I know, this is not possible in python without using any additional syntax. As you said, you cannot override = .

+1
source

To understand what l1 = l does in Python, read Other languages โ€‹โ€‹have โ€œvariables,โ€ Python has โ€œnames . โ€

To change l[0] = 1 , you can override the l __setitem__() method:

 >>> class L(list): ... def __setitem__(self, i, v): ... list.__setitem__(self, i, 10) ... >>> l = L() >>> l.append(1) >>> l [1] >>> l[0] = 0 >>> l [10] 

To change what l = List(); l = [0,1,2] l = List(); l = [0,1,2] allows you to define the List.__del__() method in CPython and to manipulate the namespace l , belongs, for example, using the inspect module. Needless to say, you should never do this.

 >>> import inspect >>> class L: ... def __del__(self): ... inspect.currentframe().f_globals['l'] = [1,2,3] ... >>> l = L() >>> l = [0] >>> l [1, 2, 3] 
+1
source

Source: https://habr.com/ru/post/909283/


All Articles