Is there a more pythonic way to do this?
if authenticate:
connect(username="foo")
else:
connect(username="foo", password="bar", otherarg="zed")
Is there a more pythonic way to do this?
if authenticate:
connect(username="foo")
else:
connect(username="foo", password="bar", otherarg="zed")
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)
The OP's version is actually ok in this case where the number of unconditional arguments is low compared to the number of conditional ones. This is because only the unconditional arguments have to be repeated in both branches of the if-else construct. However, I often run into the opposite case, i.e. the number of unconditional arguments is high compared to that of the conditional ones.
This is what I use:
connect( username="foo",
**( dict( password="bar", otherarg="zed") if authenticate else {} ) )