What does “global variables are bad” mean?

前端 未结 3 1475
野的像风
野的像风 2021-02-06 15:11

So I can read from a global variable

def f() :
  print x

And I can also assign it

def g()
  global x
  x = 3

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-06 15:11

    The problem is not so much "global == bad" so much as "Global mutable state makes it hard to reason about program flow"

    To illustrate, imagine this function:

    def frob():
        if my_global:
            wibble()
        else:
            wobble()
    

    That is, frob()s behavior depends on state whos nature is not obvious from either the body of frob(), nor from any code that might have called it. You have to try to figure out what changes my_global, and when those changes happen in relation to when frob() is called.

    When programming small scripts, this isn't much of a problem, you can see and understand all of the places that the global variable changes, and probably sort out in your head when it changes and when the dependent bits are invoked. In large programs, that's much more effort, to the point that global mutable state is widely regarded as an anti-pattern.

提交回复
热议问题