0

Is it good practice to return an object that is passed by reference and manipulated in a function?

Which of these two approaches is more pythonic? Not returning a manipulated object in place or to return it:

def append42(mylist: list) -> None:
    mylist.append(42)
def append42(mylist: list) -> list:
    mylist.append(42)
    return mylist

The latter looks nicer to me, but it is ambiguous as the function can be used in two different ways to get the same result, e.g.:

mylist = [1, 2, 3]
append42(mylist)
print(mylist)
>>> [1, 2, 3, 42]

or

mylist = [1, 2, 3]
stillmylist = append42(mylist)
assert stillmylist == mylist
print(stillmylist)
>>> [1, 2, 3, 42]
SmCaterpillar
  • 6,683
  • 7
  • 42
  • 70
  • 1
    From the persective of functional programming, I'd advise against functions with side-effects. If possible, functions should be pure, i.e. should not modify their input. Your specific question seems academic. Why would you write a function to append 42 to a list? Do you have an actual use case? That being said, you could return a *new* list with 42 added: `return [*mylist, 42]` – Richard Neumann Jan 22 '22 at 13:21
  • I'd argue against the second form simply because it can lead to the [Mutable Default Argument problem](https://stackoverflow.com/q/1132941/5987). And I agree with @RichardNeumann, a function without side effects is much easier to work with. It's trivial to assign the output of a function back to the original variable if necessary. – Mark Ransom Jan 22 '22 at 14:10

0 Answers0