Álvaro
Álvaro

Reputation: 2588

How to pass a different argument conditionally

I want to be able to change an argument to a function when a condition is met.

Currently I am doing this which works, but I am repeating the first argument, is there a way to just change the second argument?

credential = './credentials.json'

if os.path.exists(credential):
  account = authenticate(client_config=secrets, credentials=credential)
else:
  account = authenticate(client_config=secrets, serialize=credential)

Upvotes: 2

Views: 68

Answers (4)

NirO
NirO

Reputation: 217

An elegant way is to use kwargs:

credential = './credentials.json'
key = "credentials" if os.path.exists(credentials) else "serialize"
auth_kwargs = {"client_config": secrets, key: credential}    

account = authenticate(**auth_kwargs)

Upvotes: 3

Michael Butscher
Michael Butscher

Reputation: 10959

There is functools.partial for this:

from functools import partial

credential = './credentials.json'

auth = partial(authenticate, client_config=secrets)

if os.path.exists(credential):
  account = auth(credentials=credential)
else:
  account = auth(serialize=credential)

Upvotes: 1

Ron Serruya
Ron Serruya

Reputation: 4426

I think your way is fine too, but you can do this

credential = './credentials.json'
params = {'serialize': credential}
if os.path.exists(credentials):
  params['credentials'] = params.pop('serialize')

account = authenticate(client_config=secrets, **params) 

Upvotes: 2

Maurice Meyer
Maurice Meyer

Reputation: 18106

You can pass an (unpacked) dictionary to a function:

credential = './credentials.json'
arguments = {'client_config': secrets, 'serialize': credential}  # default

if os.path.exists(credentials):
    arguments.pop('serialize')
    arguments['credentials'] = credential

account = authenticate(**arguments)

Upvotes: 1

Related Questions