Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Update vs copy methods
#1
I am pretty new to python and I have a question regarding best practices that I didn't find an answer for. The problem is simple: you have a class that should have a method to update an object of such class. My question is if it is better to make a copy of that object or modify it in place. For example most pandas methods allow both and you can select using argument 'inplace'. As I see it, the options are following:

from copy import copy

class Foo:

    def __init__(self, x):
        self.x = x

    def update_only(self, x):
        self.x = x

    def update_and_return(self, x):
        self.x = x
        return self

    def copy_and_update(self, x):
        new = copy(self)
        self.x = x
        return new

    def create_updated(self, x):
        new = self.__class__(x)
        return new
What method would you use in your project? My concerns are mostly about testing and maintaining the code. Please share anything: ideas, experience, links to articles, links to github projects with examples, ...
Reply
#2
you can use one method and return always, just ignore the return value if not wanted, it will return None anyway if you don't specify a value. Having too many choices , in my opinion, is worse than not having enough.
Reply
#3
I definitely agree. I want to keep only one method and use the concept throughout entire project. But I'm currently not sure which way is the best.
Reply
#4
I just recommended the one with the return in my previous post.
Python will return None automatically if you don't specify a value.
Reply
#5
Hello jankislinger,

From my point of view: I always try to make my classes as simple and clear as possible. I would keep in your class only method for update the property:

class Foo:

	def __init__(self, x):
		self.x = x

	def update_x(self, x) -> "Foo":
		self.x = x
		# This is handy for chain update like: Foo().set_x(True).set_y(False)
		return self
If your class contains properties of another classes and you are considering class copying then it can make sense to rewrite special method __copy__ and manage how properties will be handled in copy process:

class Foo:

	def __init__(self, x):
		self.x = x

	def update_x(self, x) -> "Foo":
		self.x = x
		# This is handy for chain update like: Foo().set_x(True).set_y(False)
		return self

	def __copy__(self) -> "Foo":
		return type(self)(copy(self.x))
This can be appropriate minimum for your class. Methods like copy_and_update() or create_updated() are not necessary because you are able to do it on one line out of the class. So you keep the class neat which makes also test more clear.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020