Hi, I don’t understand this:
- The Function model returns parameters
- Within the above function model another function named optimize is called and it returns some three other variables but not parameters
- Within the above function named optimize another function named update_parameters is called and yes, this function returns parameters
- However, to my simple mind, even though the parameters are returned by the function update_parameters to the function optimize, they do get lost in the function optimize because this function does not return parameters.
The question is: how come the parameters are anyhow retrieved and passed over to the function model and - in the end - returned by this function?
Hello @Agnieszka_Sawicka,
It is a great question! Thank you for elaborating your question so clearly.
The key here is that optimize accepts parameters as an input argument. There is something special about parameters - it is a dict. When you pass a dict into a function, the function does not receive a copy of that dict, but like the “address” of that dict. Therefore, when update_parameters makes changes to that dict, it modifies directly the dict passed by optimize.
Let’s get the relations clearly: model(...) creates the parameters. Let’s say model is the “owner” of that parameters. We pass the “address” of parameters to optimize(...), then to update_parameters(...) where we actually makes modifications. Since only the “address” was passed into update_parameters(...), any modification is made directly on the parameters “owned” by model(...). This is how we can update the content of a dict in a function without returning it from a function.
You might also play with the following example to see its effect:
a_dict = {'hello': 'world'}
def update_a_dict(a_dict):
a_dict['hello'] = 'world_world'
return None
update_a_dict(a_dict)
print(a_dict)
Cheers,
Raymond
1 Like