【问题标题】:Are there problems declaring variables in conditionals?在条件中声明变量是否有问题?
【发布时间】:2018-02-25 00:50:24
【问题描述】:

在条件的所有可能分支中重新定义变量之前,是否可以防止出现问题?

例如应该这样的代码:

    # Condition could fail
    try:
        textureIndices = someExpression()

    # textureIndices is defined here if it does
    except:
        textureIndices = []

    return textureIndices

改写成这样:

    # textureIndices is defined early and then re-defined in the conditional
    textureIndices = None

    try:
        textureIndices = someExpression()


    except:
        textureIndices = 66

    return textureIndices

或者,因为except开启了其他问题,是不是这里textureIndices的定义有问题:

if condition:
    textureIndices = someExpression()

else:
    textureIndices = 66

return textureIndices 

减少问题?

唯一的区别在于第二个版本textureIndices 是在条件之外定义的。

我不明白为什么它很重要,因为不可能在条件中不为 textureIndices 分配值,但我可以看到为什么从内务角度来看,知道变量被分配给某物是件好事。

例如 if 第一个示例中没有 except 语句,那么 textureIndices 不会总是被定义,return 会导致错误。

但是,如果不转发定义在条件的两个原因中定义的变量,会有问题吗?

【问题讨论】:

  • 在第一种情况下,您使用except 而不是except SomeError。由于您不应该将所有错误都放在一起,因此在良好实践中,您的变量可能不存在,除非您之前定义它。
  • “应该重写”的出处是什么?编译器和运行时系统对此很好。

标签: python conditional-statements


【解决方案1】:

创建变量时会修改变量字典(localsglobals,具体取决于范围)。

在一种情况下,您正在创建变量,然后修改它的任何分支:1 创建+分配,1 分配(完全覆盖旧值)。

在您省略预先创建的情况下,您只有 1 个创建+分配,因此从技术上讲,在分支之前声明它会更快不是(少一个字典查找,少一个无用的分配)

除了帮助 Python IDE 完成分支中的变量名之外,我想说的是,在这种情况下,先前的声明是无用的,甚至很麻烦,因为两个分支都被覆盖了(可能是旧的编译语言编程反射)。它可能感兴趣的唯一情况是一组复杂的分支,您只需在几个分支中设置变量。这里不是这样。

【讨论】:

  • 这里不是这样,但通常您不应该具体说明您捕获的错误吗?即使您只捕获 2 个特定错误而其余的错误使您的脚本崩溃,您也必须定义两次默认值,这不会破坏 DRY(以非常小的方式)吗?
  • 不确定你在说什么。当然 try/except 没有异常类型(甚至Exception)是不好的做法。它甚至可以捕获 CTRL+C。但这似乎与问题无关。
  • @roganjosh 我当然不是在暗示这一点!反对票消失了……好的,很好。现在我永远不会知道为什么:)
  • @roganjosh 在我们批评 OP 代码时,textureIndices = [thing for thing in func()] 对于textureIndices = list(func()) 来说太过分了 :)
  • 批评可能是一个更好的词 :) 我认为这是一个很好的问题,只是这个例子并不能完全说明这种情况,在 except 中定义事物是一个坏主意,它只突出显示理解上的差距,我老了很多:)
【解决方案2】:

一个原因是它创建了冗余代码。在这种情况下,这似乎不是很明显,但举个例子,您有多个唯一的 except 语句在您的代码中捕获多个异常。想象一下,如果有人想重构您的代码或添加额外的 except 语句。

textureIndices = None

try :
    textureIndices = [thing for thing in func()]fail

except InvalidTextException:
    textureIndices = []
    #lines to handle specific exception
except ValueError:
     textureIndices = []
     #lines to handle specific exception
except OSError:
     textureIndices = []
     #lines to handle specific exception

return textureIndices

如果您有多个以这种方式表现的变量,您可以看到这种情况如何迅速升级。通过首先声明基本情况,您可以减少冗余。

textureIndices = []

try :
    textureIndices = [thing for thing in func()]fail

except InvalidTextException:
    #lines to handle specific exception
except ValueError:
     #lines to handle specific exception
except OSError:
     #lines to handle specific exception

return textureIndices

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-28
    • 2016-12-10
    • 2011-06-11
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多