What's the pythonic way of conditional variable initialization?

前端 未结 5 1790
名媛妹妹
名媛妹妹 2021-02-07 16:51

Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter. Since conditionals do not introduce new scope, constructs in other l

5条回答
  •  逝去的感伤
    2021-02-07 17:08

    In general second approach is better and more generic because it doesn't involve calling get_message unconditionally. Which may be ok if that function is not resource incentive but consider a search function

    def search(engine):
        results = get_from_google()
        if engine == 'bing':
           results = get_from_bing()
    

    obviously this is not good, i can't think of such bad scenario for second case, so basically a approach which goes thru all options and finally does the default is best e.g.

    def search(engine):
        if engine == 'bing':
           results = get_from_bing()
        else:
           results = get_from_google()
    

提交回复
热议问题