How Can I "override" Deepcopy In Python?
I'd like to override __deepcopy__ for a given SQLAlchemy-mapped class such that it ignores any SQLA attributes but deepcopies everything else that's part of the class. I'm not part
Solution 1:
When (deep-)copying you should not be calling __init__
but instead call __new__
.
An example:
def__copy__(self):
cls = self.__class__
newobject = cls.__new__(cls)
newobject.__dict__.update(self.__dict__)
return newobject
Solution 2:
mavnn is right. For example try change your init of User to:
def__init__(self, user_id = None, name = None):
self.user_id = user_id
self.name = name
As for copying mapped instances, I recommend reading this thread
Solution 3:
I'm not an expert on deepcopy, but from the error it looks like you need a parameterless constructor to call self.__class__()
without parameters.
Solution 4:
To exclude sqlalchemy columns and mapped attributes you would do something along the lines of:
for attr indir(self):
ifnot self._sa_class_manager.mapper.has_property(key):
...
Post a Comment for "How Can I "override" Deepcopy In Python?"