Does the Python standard library offer anything similar to the custom replace function below? I can put this in my own *utils module, but I'd rather use a standard library implementation. Also, this example would better be served by a namedtuple, which already has _replace, but I need the same function for other classes in my project.
from copy import copy
class cab(object):
a = None
b = None
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "cab(a=%s, b=%s)" % (self.a, self.b)
# Does not modify source. Creates a copy with the specified modified fields.
def replace(source, **kwargs):
result = copy(source)
for key in kwargs:
setattr(result, key, kwargs[key])
return result
v1 = cab(3,4)
v2 = replace(v1, a=100)
v3 = replace(v1, b=100)
-
1No, this isn't built-in; why would it be? If you need it in custom classes, why not make a mix-in instance method?jonrsharpe– jonrsharpe2015年06月09日 17:11:16 +00:00Commented Jun 9, 2015 at 17:11
1 Answer 1
namedtuple
has such a method because it itself is immutable. Other immutable types in the standard library have one too, like datetime.datetime
for example.
It is not a common pattern to use with mutable objects. So no, there is no built-in version for custom types for this. Custom classes invariably require custom handling anyway.
Note that your utility is a function, and not a method either. You'd usually make it a method on custom classes:
class cab(object):
a = None
b = None
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "cab(a=%s, b=%s)" % (self.a, self.b)
def replace(self, **kw):
return type(self)(kw.get('a', self.a), kw.get('b', self.b))
-
This is a common pattern with immutable types. Was that a typo? Python classes, of course, are mutable.clay– clay2015年06月09日 19:08:53 +00:00Commented Jun 9, 2015 at 19:08
-
A function seems much more logical than a method, because you only need one function that works on any data type, as opposed to having to add the method to every class that you want to support.clay– clay2015年06月09日 19:10:22 +00:00Commented Jun 9, 2015 at 19:10
-
1@clay: but that assumes that any class is like any other. That's hardly ever true.Martijn Pieters– Martijn Pieters2015年06月09日 20:15:20 +00:00Commented Jun 9, 2015 at 20:15