Python nested scopes with dynamic features

前端 未结 2 703
无人及你
无人及你 2021-02-07 19:59

Need help with understanding the following sentence from PEP 227 and the Python Language Reference

If a variable is referenced in an enclosed scope, it is

2条回答
  •  Happy的楠姐
    2021-02-07 20:19

    An example can be this one:

    >>> def outer():
    ...     x = 0
    ...     y = (x for i in range(10))
    ...     del x
    ... 
    SyntaxError: can not delete variable 'x' referenced in nested scope
    

    Basically it means you can't delete variables that are used in inner blocks(in that case the genexp).

    Note that this apply for python <= 2.7.x and python < 3.2. In python3.2 it's it does not raise syntax error:

    >>> def outer():
    ...     x = 0
    ...     y = (x for i in range(10))
    ...     del x
    ... 
    >>> 
    

    See this link for the whole story of the change.

    I think the python3.2 semanthics is more correct because if you write the same code outside a function it works:

    #python2.7
    >>> x = 0
    >>> y = (x for i in range(10))
    >>> del x
    >>> y.next()     #this is what I'd expect: NameError at Runtime
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 1, in 
    NameError: global name 'x' is not defined
    

    While putting the same code into a function, not only changes exception but the error is at compile time.

提交回复
热议问题