I have the following json input parameters file
#input.json
{
"nx": 401,
"ny": 401,
"T" : 10,
"nt" : 20,
"D" : 0.2,
"Sgma": 0.243,
"M": 0.0052
}
that is passed onto different python
scripts, for eg.
#test1.py
import numpy,os
def simple(nx,ny,D,Sgma, M, T,nt): #parameters as function arguments
k = Sgma 0.02
print("this is domain size", ny)
print("this is dif time", T)
print("this is K param", k)
#test2.py
import numpy,os
def simple_n(nx,ny,D,Sgma,M,T,nt): #parameters as function arguments
k = M 0.02
print("this is domain size", ny)
print("this is sim time", D)
print("this is K param", k)
I execute both the above python
scripts through a main.py
that passes the input parameters with argparse.
As you can see, only some, not all of the parameters are required in individual scripts. My question: Is there a way to pass only the required arguments in simple()
?
For example: def simple(ny,T,k)
for test1.py
and def simple(ny,D,k)
for test2.py
rather than def simple(nx,ny,D,Sgma, M,T,nt)
. Since I will be dealing with large sets of parameters as initial config, I would like to know an efficient way to pass the initial parameters in different python
codes as function arguments. Thanks
CodePudding user response:
You can use **kwargs
for that. It is a pattern often used in python where you pass named parameters to a function and inside the function you access the values you need.
def simple(**kwargs):
ny = kwargs.get('ny', None)
if ny is None:
print("Parameter 'ny' is required.")
# Call the function with only required arguments
simple(ny=1, D=15, nt=2)
Or you could add default values to your function and pass values by their name.
def simple(nx=0, ny=0, D=0, Sgma=0, M=0, T=0, nt=0):
pass
# Call the function with only required arguments
simple(ny=1, D=15, nt=2)
UPDATE
a = {"foo": "bar", "baz": 1}
def simple(foo=None, bar=None, baz=None):
print(foo)
print(bar)
print(baz)
>>> simple(**a)
bar
None
1