If I have a function that returns multiple outputs, from which some aren't needed at times, I found that it is a convention to "ignore" these outputs with underscore, e.g.
a, _ = fn_with_two_outputs()
Until now I assumed that the value is just dropped and naively hoped that the compiler is clever enough not to execute any code associated with the value. But in a recent debugging session I noticed that this method actually creates a variable _
with the output - which is a waste of memory and should discourage from using the underscore-convention, shouldn't it?
I'm now leaning to this variant:
a = fn_with_two_outputs()[0]
that I found among other ways of "ignoring output", since as far as I tested it, at least it doesn't store the output fn_with_two_outputs()[1]
as a variable in the environment calling the function (it IS stored in the function environment itself). To avoid discussion: To get several return values without calling twice one can use slicing, e.g. fn_with_two_outputs()[0:4]
.
But: The return value - if "ignored" or not - always seems to be evaluated. I tested this for three variants of "ignoring" it with below code.
def fn_with_two_outputs():
a = [1, 2, 3]
b = [0, 0, 0]
return a, needless_fn(b)
def needless_fn(b):
print("\"Be so good they can't ignore you.\" - Steve Martin")
return b
# I want to ignore output b (wrapped by needless_fn)
a, _ = fn_with_two_outputs() # stores _ = b, needless_fn was executed
a, *b = fn_with_two_outputs() # suggested for Python3, stores a list b = [b], needless_fn was executed
a = fn_with_two_outputs()[0] # b nowhere to be found, but needless_fn was executed
Is there a convenient way to actually ignore the output IN the function itself, causing the optional output not to consume any memory and cause code execution? My first idea is, give fn()
a parameter to branch between two return statements, one "lazy", the other not - but that seems more like a workaround than an elegant solution.