I need a lot of small objects in my applications. They must be immutable and return a new instance when I set a new attribute.
I found a lot of ways to disable the obj.prop = newValue
behavior, now I need this:
newObj = obj.setTitle(title)
newObj = obj.setDirection(x, y)
newObj = obj.incrementCount()
newObj = obj.swap()
Currently I do this:
class Info(object):
__slots__ = ['_x', '_y', ...]
def setDirection(self, x, y):
newObj = copy.copy(self) # shallow copy is OK
newObj._x = x
newObj._y = y
return newObj
def swap(self):
newObj = copy.copy(self)
# methods can do different things
newObj._x, newObj._y = self._y, self._x
return newObj
Is this good in terms of perfomance? Are there any faster ways to return a clone of the object with some attributes changed?
I use __slots__
. My object has predefined properties. I have no generic .set(prop, value)
methods
(Python 3.5+ is welcome)