-1

In Python variables that are created outside of a function are known as global variables. However to create a global variable inside a function (a local variable), you can use the global keyword.

My question is, what are the situations for when a global variable should be inside or outside a function?

1
  • 3
    See this, this, this & this. "what are the situations for when a global variable should be inside [...] a function" - as a rule of thumb, try to avoid that; the problem with globals is that they are global :) Commented Nov 15, 2019 at 8:20

2 Answers 2

0

Think of caching a precondition, which could be expensive to compute, but is checked frequently, e.g. on every function call. Then it could make sense to store a boolean of the precondition once, and it use it within the function. But I guess there are more elegant patterns to avoid such tricks. I would consider it quick and dirty hack. You can also have a function global variable like this:

def f():
   if f.precondition is None:
       f.precondition = test_precondition()

   if f.precondition:
      # ...
   else:
      #...
# set the initial state
f.precondition = None

That way you avoided to use a global variable, but reduced the scope to be somehow static to a particular function. The value can also be shared across function.

0

I would always recommend declaring your global (module level) variables outside of the function scope. If you declare it locally, you need to make sure that method has executed before accessing it in another method. While that can be done, it's a bit of a booby trap when making changes. By declaring it at the module level it sets up a clear expectation of the intended use.

You may be missing one thing about this, however. Even if you declare the variable at the module scope, you need to have the global declaration in your local scope in order to assign a value to it. Otherwise, the assignment will create a new name in the local scope that shadows the global name. I personally find this feature of Python to be one of it's worst warts. If you are using global scope a lot in a module, you should consider refactoring to use classes instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.