Global keyword on module scope

87 views Asked by At

I have a Python file that have the following lines:

import sys

global AdminConfig
global AdminApp

This script runs on Jython. I understand the use of global keyword inside functions, but what does the use of the "global" keyword on module level mean?

1

There are 1 answers

0
ch3ka On

global x changes the scoping rules for x in current scope to module level, so when x is already at the module level, it serves no purpose.

To clarify:

>>> def f(): # uses global xyz
...  global xyz
...  xyz = 23
... 
>>> 'xyz' in globals()
False
>>> f()
>>> 'xyz' in globals()
True

while

>>> def f2():
...  baz = 1337 # not global
... 
>>> 'baz' in globals()
False
>>> f2() # baz will still be not in globals()
>>> 'baz' in globals()
False

but

>>> 'foobar' in globals()
False
>>> foobar = 42 # no need for global keyword here, we're on module level
>>> 'foobar' in globals()
True

and

>>> global x # makes no sense, because x is already global IN CURRENT SCOPE
>>> x=1
>>> def f3():
...  x = 5 # this is local x, global property is not inherited or something
... 
>>> f3() # won't change global x
>>> x # this is global x again
1