Is there a more pythonic way to do this?
if authenticate:
connect(username="foo")
else:
connect(username="foo", password="bar", otherarg="zed")
Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.
A keyword argument is a name-value pair that is passed to the function. Here are some of the advantages: If the values passed with positional arguments are wrong, you will get an error or unexpected behavior. Keyword arguments can be passed in any order.
Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.
Positional arguments must be passed in order as declared in the function. So if you pass three positional arguments, they must go to the first three arguments of the function, and those three arguments can't be passed by keyword.
You could add them to a list of kwargs like this:
connect_kwargs = dict(username="foo")
if authenticate:
connect_kwargs['password'] = "bar"
connect_kwargs['otherarg'] = "zed"
connect(**connect_kwargs)
This can sometimes be helpful when you have a complicated set of options that can be passed to a function. In this simple case, I think what you have is better, but this could be considered more pythonic because it doesn't repeat username="foo"
twice like the OP.
This alternative approach can also be used, although it only works if you know what the default arguments are. I also wouldn't consider it to be very "pythonic" because of the duplicated if
clauses.
password = "bar" if authenticate else None
otherarg = "zed" if authenticate else None
connect(username="foo", password=password, otherarg=otherarg)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With