Python 2.x gotchas and landmines

后端 未结 23 2298
北恋
北恋 2020-11-28 17:47

The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp

23条回答
  •  旧巷少年郎
    2020-11-28 18:10

    You cannot use locals()['x'] = whatever to change local variable values as you might expect.

    This works:
    
    >>> x = 1
    >>> x
    1
    >>> locals()['x'] = 2
    >>> x
    2
    
    BUT:
    
    >>> def test():
    ...     x = 1
    ...     print x
    ...     locals()['x'] = 2
    ...     print x  # *** prints 1, not 2 ***
    ...
    >>> test()
    1
    1
    

    This actually burnt me in an answer here on SO, since I had tested it outside a function and got the change I wanted. Afterwards, I found it mentioned and contrasted to the case of globals() in "Dive Into Python." See example 8.12. (Though it does not note that the change via locals() will work at the top level as I show above.)

提交回复
热议问题