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)
asked Jun 9, 2015 at 16:56
1
  • 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? Commented Jun 9, 2015 at 17:11

1 Answer 1

2

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))
answered Jun 9, 2015 at 17:55
3
  • This is a common pattern with immutable types. Was that a typo? Python classes, of course, are mutable. Commented 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. Commented Jun 9, 2015 at 19:10
  • 1
    @clay: but that assumes that any class is like any other. That's hardly ever true. Commented Jun 9, 2015 at 20:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.