Consider an instance of a class:
class Car(object):
def __init__(self):
self.engine = None
And a function that modifies that instance:
def add_engine(car):
car.engine = 'V6'
Python has no implicit techniques of pointing out that an argument will be modified. The best solution that I could think of is to return the modified object (even though it will be the same object passed as an argument):
def add_engine(car):
car.engine = 'V6'
return car
How would you solve this design issue?
—
Guys, thank you very much for answering. Your advices helped to clear the mess in my head 🙂
I tend to make these things methods that return
self. That allows constructs likeThe other option, which is sometimes used in the Python standard library, is not to return anything. That’s supposed to prevent confusion and force an imperative style on the client when they use destructive updates.
list.sortvs.sortedis an example of this.The choice is one of style, so the usual rules of consistency with surrounding code apply.