代码之家  ›  专栏  ›  技术社区  ›  matt wilkie

做什么尝试:早点退出?

  •  2
  • matt wilkie  · 技术社区  · 14 年前

    在下面的函数中 try: 提前退出?如果我把相同的代码放在 def 阻止它工作正常。

    tiles = ['095D', '094M']
    in_file = 'in_file'
    out_file = 'out_file'
    expression = ''' "FIELDNAME" LIKE 'STUFF' '''
    
    def foobar(in_file, out_file, expression):
        print in_file, out_file, expression
        try:
            print 'this is trying'
            #pretty print tile list, from http://stackoverflow.com/questions/2399112/python-print-delimited-list
            tiles = ','.join(map(str,tiles))
            print 'made it past tiles!'
            print 'From %s \nselecting %s \ninto %s' % (in_file, tiles, out_file)
    
        except:
            print 'Made it to the except block!'
    
    foobar(in_file, out_file, expression)
    

    结果:

    D:\> python xx-debug.py
    in_file out_file  "FIELDNAME" LIKE 'STUFF'
    this is trying
    Made it to the except block!
    

    结果与 same code not in a def :

    this is trying
    made it past tiles!
    From in_file
    selecting 095D,094M
    into out_file
    
    3 回复  |  直到 14 年前
        1
  •  3
  •   Blixt    14 年前

    它不起作用的原因是你定义了 tiles 在全球范围内。在你分配给的函数中 瓷砖 . 这使得 瓷砖 函数中的本地作用域名称。反过来,这意味着函数中的代码不会查找 瓷砖 在全球范围内。

    在作业中,你试图 得到 瓷砖 (这是在本地分配之前发生的。)这会导致引发异常,因为您试图访问未分配的本地变量。

    快速的解决方法是使用 global :

    ...
    def foobar(in_file, out_file, expression):
        global tiles
        ...
    

    正如其他人所说,不要只抓住例外而不采取行动。在调试代码时,您 希望 要抛出异常以便查找并修复原因!或者移除 try ... except ,或使 除了 创建一个异常并打印有关它的有用信息,如下所示:

    try:
        ...
    except Exception, e:
        print 'Oh noes!', e
    

    这可能需要阅读很多内容,但如果您确实阅读了Python,您将更了解它:

    http://docs.python.org/reference/executionmodel.html

    它解释了Python如何处理模块作用域和函数作用域等中的变量定义,还包括异常。

        2
  •  3
  •   Mike    14 年前

    异常输出:

    Traceback (most recent call last):
      File "sof.py", line 19, in <module>
        foobar(in_file, out_file, expression)
      File "sof.py", line 11, in foobar
        tiles = ','.join(map(str,tiles))
    UnboundLocalError: local variable 'tiles' referenced before assignment
    

    现在,这是因为tiles实际上是在 全球的 空间。所以,你的函数应该是这样的:

    def foobar(in_file, out_file, expression):
        global tiles
        ...
    
        3
  •  -1
  •   jpsimons    14 年前

    你的虫子真有趣。所以有一个模块的作用域 tiles 在函数之外,因为你不使用 global ,您正在创建一个新的 瓷砖 函数中的变量。这很好。或者它也可以,除了它看起来(当我在交互式Python中陷入困境时)语句的左值( 瓷砖 在左边)是局部的,使得整个语句认为任何对tiles的引用都意味着局部的。所以在这个map结构中,不是使用模块 tites 它使用本地的一个,但本地的一个还不存在。

    这可能是Python中的一个bug,但可能正是预期的。