Python: Why is global needed only on assignment and not on reads?

前端 未结 4 1122
一向
一向 2020-12-09 15:00

If a function needs to modify a variable declared in global scope, it need to use the global declaration. However, if the function just needs to read a global variable it ca

4条回答
  •  [愿得一人]
    2020-12-09 15:35

    Look at this code:

    from module import function
    
    def foo(x):
        return function(x)
    

    The name function here is a global. It would get awfully tedious if I had to say global function to get this code to work.

    Before you say that your X and my function are different (because one is a variable and the other is an imported function), remember that all names in Python are treated the same: when used, their value is looked up in the scope hierarchy. If you needed global X then you'd need global function. Ick.

提交回复
热议问题