Skip to content

Instantly share code, notes, and snippets.

@mwcraig
Created April 3, 2019 13:21
Show Gist options
  • Save mwcraig/cd88b07e1b4bcda2af33ec5a430690f4 to your computer and use it in GitHub Desktop.
Save mwcraig/cd88b07e1b4bcda2af33ec5a430690f4 to your computer and use it in GitHub Desktop.
### Define a function with kwargs
def kwargs_fun(**kwargs):
# Just print the content of kwargs
print(kwargs)
# Now call kwargs_fun in a few goofy ways and see what happens:
kwargs_fun(matt='short', shoe_size=9.5, hair=True)
kwargs_fun(g=9.8, foo=-9)
# Define this function for an example of how to pass kwargs
# through a function without ever looking at what is inside. This
# function is kind of like rk2 and make_solve.
def kwargs_caller(f, **kwargs):
f(**kwargs)
# Call our new function
kwargs_caller(kwargs_fun, g=10, planet='earth')
# A revised version of our "func" from lecture:
def func(conditions, t, g=9.8):
y = conditions[0]
vy = conditions[1]
# print the value of g just to see what its value is in here
print("Field strength is ", g)
return [vy, -g]
# One last definition, a revised kwargs_caller that passes on
# conditions and time
def kwargs_caller2(f, cond, t, **kwargs):
f(cond, t, **kwargs)
# Initials conditions
cond_init = [0, 0.0]
t = 0.0
# And call it with our caller (which is like rk2 or make_solve):
kwargs_caller2(func, cond_init, t, g=5) # Works, and g=5 in func
kwargs_caller2(func, cond_init, t) # Works, and g=9.8, the default, in func
kwargs_caller2(func, cond_init, t, g=9.8 / 6, planet='moon') # FAILS because func does not have argument planet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment