[Tutor] Fwd: Which is better style for a function that modifies a list?
boB Stepp
robertvstepp at gmail.com
Thu Jun 24 17:20:49 EDT 2021
Alan accidentally sent this to just me. See below.
---------- Forwarded message ---------
From: Alan Gauld <alan.gauld at yahoo.co.uk>
Date: Thu, Jun 24, 2021 at 3:45 AM
Subject: Re: [Tutor] Which is better style for a function that modifies a list?
To: boB Stepp <robertvstepp at gmail.com>
Sending from a phone so not a full-size response, but I had to chip i
my tuppence worth….
> On 24 Jun 2021, at 00:59, boB Stepp <robertvstepp at gmail.com> wrote:
>
> def remove_last_item(L: list) -> list:
> """Return list L with the last item removed."""
>
> del L[-1]
> return L
>
> does not require the return statement since the original passed in
> list will be modified in place, so there is no need for the function
> to return anything.
> 1) For such a function that mutates the passed-in list is it
> clearer/better style to keep or omit the return statement? Which
> reads better?
>
Functions should return something unless they “do” nothing - eg print()
But if they modify something they should return it - that’s what
functions do, its in their definition. So even if they, as a
side-effect, modify an argument it is still good practice to return
the modified item as well. It also allows more consistent code, with
all function usage following the form of
Result = function(args)
Unfortunately many Python methods do not follow this form, but most of the
built in functions do - eg sorted(), etc.
The argument for methods not returning values is that the modification is to
the object which is being messaged so it doesn’t need to return a value
(although other OOP languages recommend returning self to enable chaining)
> 2) From a preventative of subtle bugs perspective, if one must alter
> a passed-in list, would it be better to do a deep copy of the list
> passed in, mutate that, and return *that* list, leaving the original
> passed-in list unaltered?
That’s what the pure functional programming school says (and what
python does with string methods) but pragmatically it can be a huge
consumer of memory and potentially very slow so its better to just
return the modified item IMHO.
Alan G
(Still on my hols)
More information about the Tutor
mailing list