I was wondering if there was a way to do something like this in Python:
some_method(param1="param1", param2 = somevar or None)
I want to pass the param2 if somevar is set, or None if it isn’t. Basically I am looking for a shorter way of doing this:
if somevar is None:
some_method(param1="param1")
else:
some_method(param1="param1", param2=somevar)
Keyword arguments default to what you provide them in your function definition.
Consider:
If you want to print the value of a local variable, you can do so by adding the expected variable name to your definition:
Then, if you define a variable with that name:
But don’t do this — it is unexpected, magic and definitely un-Pythonic — pass the value you need in as your second parameter instead.
If you need to be able to call it with that variable without errors, then make sure to define that variable at the top of your module.