So I’m using different parameter dictionaries for different calibrations of my model by passing each time a different parameters dict to the model functions as argument. So I was wondering what is the most elegant way to unpack these parameters inside a function i.e. populate the local namespace of the function with these parameters without having to manually assign them? I hope I’m clear enough
Thanks a lot for the answer. That’s more or less what I do. The trouble with this is that I have to write all the parameters everytime I unpack the dict. Is there any way to loop over the dict keys and values and do the assignment within the loop?
That would be great.
Thanks a lot @john.stachurski for the suggestion. What I’m trying to do is to pass the whole parameters dict to the function and then unpack inside it. By doing this I’m trying to avoid having the parameters as global variables and also handling the use of different sets of parameters for the purpose of model calibration without resorting to OOP.
I found some people suggesting the use of locals().update(dict) but I haven’t tried it yet.
Sorry to get to this discussion late. I have one last thought on this – If you don’t want to build up a full class or if you wanted to pass these parameters into a numba function then you could use what is called a namedtuple (https://docs.python.org/3.6/library/collections.html#collections.namedtuple). It isn’t that different than OOP, but is a little lighter and is compatible with numba.
Here is a very contrived example of what that might look like
from collections import namedtuple
from numba import jit
# This is a simple model where agent always will
# consume one unit of consumption good.
# Utility is CRRA with risk aversion gamma and
# discounts future with beta
MyModel = namedtuple("MyModel", ["beta", "gamma"])
@jit(nopython=True)
def utility(m, c):
return (c**(1-m.gamma) / (1-m.gamma))
@jit(nopython=True)
def solve(m):
"""
Simple model where agent always gets 1 consumption.
This function solves for corresponding VF...
Insert more fancy and instructive documentation here
"""
V = 0.0
dist, tol = 10.0, 1e-8
while dist>tol:
Vnew = utility(m, 1.0) + m.beta*V
dist = Vnew - V
V = Vnew
return V
Great! Thanks a lot @cc7768. These named tuples seem to be exactly what I needed! Looks similar to Matlab structures I guess. I will have a deeper look at them.