Lately I came across a way of using mutables which I had not thought of before.
Let's say you have a list comprehension which calls a method, and you put the result in a list like the following (normal stuff):
my_list = [my_object.do_stuff() for my_object in all_objects]
do_stuff method does some loop computations to build diverse things, it's quite a bit complicated. For now everything's okay, but it turns out you need to do part of that computation again, and put the result in another list, just afterwards:
my_other_list = [my_object.do_just_a_part_of_stuff() for my_object in all_objects]
You find out that to avoid doing the same bit of computation twice, you can use a mutable like a
set the following way:
my_set = set() my_list = [my_object.do_stuff(my_set) for my_object in all_objects] my_other_variable = do_something_with(my_set)
As you can see,
my_set is empty at first, passed as an argument to
do_stuff which modifies it in place just enough while it performs the computations mentioned above, and then once modified,
my_set gets used for
Is this kind of pattern commonly considered good practice? And does it even have a name? I must say I find this quite simple and elegant, but I'm also wondering if that's not a bit hazardous and perhaps not so easy to read when you first encounter the codebase.