Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python copy : How to inherit the default copying behaviour?

Tags:

python

copy

Ok ... It might be a stupid question ... but I'm not finding the answer right now !

I need to realize the copy of an object, for which I want all the attributes to be copied, except one or two for which I want to fully control the copy.

Here is the standard copying behaviour for an object :

>>> class test(object):
...     def __init__(self, arg):
...         self._a = arg
... 
>>> t = test(123999)
>>> t._a
123999
>>> tc = copy.copy(t)
>>> tc._a
123999

Which basically means that all the attributes are copied. What I would like to do is re-use this behaviour in the following way :

>>> class test(object):
...     def __init__(self, arga, argb):
...         self._a = arga
...         self._b = argb
...
...     def __copy__(self):
...         obj_copy = copy.copy(self) #NOT POSSIBLE OF COURSE => infinite recursion
...         obj_copy._b = my_operation(obj_copy._b)
...         return obj_copy

I hope you got the point : I want to re-use the object copying behaviour, but hook-in my own operations. Is there a clean way to do this (without having to do for attr_name in dir(self): ...) ???

like image 267
sebpiq Avatar asked Dec 29 '22 10:12

sebpiq


1 Answers

You could just do:

def __copy__(self):
    clone = copy.deepcopy(self)
    clone._b = some_op(clone._b)
    return clone

This will work because deepcopy avoids recursion. From the python docs:

The deepcopy() function avoids these problems by: keeping a “memo” dictionary of objects already copied during the current copying pass; and letting user-defined classes override the copying operation or the set of components copied.

like image 172
ars Avatar answered Jan 14 '23 01:01

ars