简体   繁体   English

什么是条件变量初始化的pythonic方式?

[英]What's the pythonic way of conditional variable initialization?

Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter. 由于Python的作用域规则,之后在范围内初始化的所有变量都可用。 Since conditionals do not introduce new scope, constructs in other languages (such as initializing a variable before that condition) aren't necessarily needed. 由于条件不引入新范围,因此不一定需要其他语言的构造(例如在该条件之前初始化变量)。 For example, we might have: 例如,我们可能有:

def foo(optionalvar = None):
    # some processing, resulting in...
    message = get_message()
    if optionalvar is not None:
        # some other processing, resulting in...
        message = get_other_message()
    # ... rest of function that uses message

or, we could have instead: 或者,我们可以改为:

def foo(optionalvar = None):
    if optionalvar is None:
        # processing, resulting in...
        message = get_message()
    else:
        # other processing, resulting in...
        message = get_other_message()
    # ... rest of function that uses message

Of course, the get_message and get_other_message functions might be many lines of code and are basically irrelevant (you can assume that the state of the program after each path is the same); 当然, get_messageget_other_message函数可能是多行代码并且基本上是无关的(你可以假设每个路径之后程序的状态是相同的); the goal here is making message ready for use beyond this section of the function. 这里的目标是使message准备好在函数的这一部分之外使用。

I've seen the latter construct used several times in other questions, such as: 我已经看到后一种结构在其他问题中多次使用,例如:

Which construct would be more acceptable? 哪种结构更容易接受?

Python also has a very useful if syntax pattern which you can use here Python也有一个非常有用的if语法模式,你可以在这里使用

  message = get_other_message() if optional_var else get_message()

Or if you want to compare strictly with None 或者,如果您想严格比较无

  message = get_other_message() if optional_var is not None else get_message()

Unlike with example 1) you posted this doesn't call get_message() unnecessarily. 与示例1)不同,您发布的不会不必要地调用get_message()。

In general second approach is better and more generic because it doesn't involve calling get_message unconditionally. 通常,第二种方法更好,更通用,因为它不涉及无条件地调用get_message 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 eg 显然这不好,我不能想到第二种情况的这种不良情况,所以基本上是一种通过所有选项的方法,最后默认是最好的,例如

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

I think it's more pythonic to not set an explicit rule about this, and instead just keep to the idea that smallish functions are better (in part because it's possible to keep in your mind just when new names are introduced). 我认为没有对此设置一个明确的规则更加pythonic,而只是坚持小功能更好的想法(部分原因是因为只有在引入新名称时才能记住你的想法)。

I suppose though that if your conditional tests get much more complicated than an if/else you may run the risk of all of them failing and you later using an undefined name, resulting in a possible runtime error, unless you are very careful. 我想虽然如果你的条件测试变得比if/else复杂得多,你可能会冒所有失败的风险而后来使用未定义的名称,导致可能的运行时错误,除非你非常小心。 That might be an argument for the first style, when it's possible. 在可能的情况下,这可能是第一种风格的论据。

The answer depends on if there are side effects of get_message() which are wanted. 答案取决于是否存在get_message()副作用。

In most cases clearly the second one wins, because the code which produces the unwanted result is not executed. 在大多数情况下,显然第二个获胜,因为不会执行产生不需要的结果的代码。 But if you need the side effects, you should choose the first version. 但如果你需要副作用,你应该选择第一个版本。

It might be better (read: safer) to initialize your variable outside the conditions. 在条件之外初始化变量可能更好(读取:更安全)。 If you have to define other conditions or even remove some, the user of message later on might get an uninitialized variable exception. 如果您必须定义其他条件甚至删除某些条件,稍后的message用户可能会获得未初始化的变量异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM