Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

python - Pythonic way to pass keyword arguments on conditional

Is there a more pythonic way to do this?

if authenticate:
    connect(username="foo")
else:
    connect(username="foo", password="bar", otherarg="zed")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...