1

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)
  • 1
    No, 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 Jun 9 '15 at 17:11
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 Jun 9 '15 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 Jun 9 '15 at 19:10
  • @clay: but that assumes that any class is like any other. That's hardly ever true. – Martijn Pieters Jun 9 '15 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.