Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to pass keyword arguments on conditional

Tags:

python

Is there a more pythonic way to do this?

if authenticate:
    connect(username="foo")
else:
    connect(username="foo", password="bar", otherarg="zed")
like image 976
atp Avatar asked Dec 31 '11 04:12

atp


People also ask

How do you pass keyword arguments in Python?

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.

Can we pass keyword arguments in any order?

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.

How do you pass multiple keyword arguments in Python?

Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.

Can we pass keyword arguments in any order in Python?

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.


1 Answers

  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)
    
like image 145
jterrace Avatar answered Sep 28 '22 11:09

jterrace