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.
username="foo"
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.
if
password = "bar" if authenticate else None otherarg = "zed" if authenticate else None connect(username="foo", password=password, otherarg=otherarg)
2.1m questions
2.1m answers
60 comments
57.0k users