Python – Replace Function for Classes Similar to Namedtuple _replace

python

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)

Best Answer

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))