代码之家  ›  专栏  ›  技术社区  ›  max

python:避免在循环中赋值之前使用变量的bug

  •  2
  • max  · 技术社区  · 14 年前
    for element in container:
      # some code here
      temp_variable = f1(element)
      # more code
    
    # much later in the code
    
    for element in container:
      # some code
      another_variable = g(temp_variable)
      # more code
      temp_variable = f2(element)
      # more code
    

    在第二 for 循环,我不小心用了变量 temp_variable 在分配之前。通常,我会 NameError 异常,但不幸的是,它在前一个循环中幸存、有效并已初始化。

    是否有任何编码实践、IDE工具等有助于防止此类错误?

    顺便说一句,我在想,如果循环中的变量没有在循环结束后存活下来,可能会更好。

    编辑

    @伊格纳西奥·瓦兹奎兹·艾布拉姆斯:

    如果理解正确,建议不要在多个循环中使用与局部变量相同的变量名。我有两个问题:

    1. 通常,要使用的最具描述性的变量名在多个循环中是相同的。我用过类似的东西 unique_visitor_count . 我不想禁止这个变量在代码中或在另一个循环中被进一步使用。

    2. 在处理现有代码时,要检查我要使用的任何新变量名以前是否已经使用过,这将非常困难。

    6 回复  |  直到 14 年前
        1
  •  7
  •   aaronasterling    14 年前

    temp_variable tmp temp

        2
  •  4
  •   Rafe Kettler    14 年前

        3
  •  3
  •   eduffy    14 年前

    del temp_variable

        4
  •  3
  •   kindall    14 年前

    def myfunc(a):
    
        i = 10
    
        def infunc():
            for i in range(a):
                print i,
        infunc()
    
        print i
    
    myfunc(5)
    >>> 0 1 2 3 4 10
    

        5
  •  0
  •   GreenMatt    14 年前
        6
  •  0
  •   S.Lott    14 年前