In next two solutions I expect that you are allowed to change definition of your f(...)
function. First solution uses global variable, and second doesn't use any globals.
First variant (below) is that you can just use a global variable to store saved value.
Try it online!
def f(value):
global saved_value
saved_value = value
value = 123
a = 456
return a
# Regular usage of your function
value = 789
print(f(value)) # Prints 456
# Somewhere later in your code
# This will print saved value
print(saved_value) # Prints 789
Output:
456
789
Second variant (below) without using any global variable is by using state dictionary with default {}
value. This state does same thing as global variable, it saves value for later use. I changed number of arguments in your function but that is not a problem because as before everyone can call your function just as f(value)
, the rest of arguments are not necessary to be provided and will be considered to be equal to default values.
Try it online!
def f(value, *, state = {}, return_value = False):
if return_value:
return state['value']
else:
state['value'] = value
value = 123
a = 456
return a
# Regular usage of your function
value = 789
print(f(value)) # Prints 456
# Somewhere later in your code
# This will print saved value
print(f(None, return_value = True)) # Prints 789
Output:
456
789