Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 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 Reply

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)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...