17
votes

Is there a more pythonic way to do this?

if authenticate:
    connect(username="foo")
else:
    connect(username="foo", password="bar", otherarg="zed")
4
What's wrong with what you have? "Don't repeat yourself" is a good rule to follow, but not if it makes your code more complicated. - user97370
It won't be that much more complicated, so I value DRY over complexity in this case. - atp

4 Answers

27
votes
  1. 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.

  2. 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)
    
7
votes

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 {} ) )
2
votes

Just thought I'd throw my hat in the ring:

authenticate_kwargs = {'password': "bar", 'otherarg': "zed"} if authenticate else {}
connect(username="foo", **authenticate_kwargs)
-2
votes

Or, more concisely:

connect(**(
    {'username': 'foo', 'password': 'bar', 'otherarg': 'zed'}
    if authenticate else {'username': 'foo'}
))