This is just a curiosity question for a “good” pythonic way to do this.
I have a function with an optional parameter ie.
def foo( a, b, c='en' ):
print c
There is a dict with a bunch of info in it, and if a particular key is in the dict, I would like to pass it into foo to override c’s default, but if the key is not in the dict, I just want to use the default for c.
Obviously this will work…
if "SomeKey" in mydict:
foo( val1, val2, mydict[ "SomeKey" ]
else:
foo( val1, val2 )
And another option would be to do something like
params = [ val1, val2 ]
if "SomeKey" in mydict:
params.append( mydict[ "SomeKey" ] )
foo( *params )
but there must be a slick, more pythonic way to do this? ie.
foo( val1, val2, mydict[ "SomeKey" ] if "SomeKey" in mydict else < use default > )
Thanks in advance!
Don’t use a “true” default value for this – instead, use a placeholder value:
and then just call with…
(
.get()returnsNoneif the key isn’t in the dict, by default)If you can’t modify
foo(), then you can do the more complex varargs path: