Srikanth Bhandary
Srikanth Bhandary

Reputation: 1747

Global variables within modules in python

I am new to python and started with some of the basic example and found a question that is does an imported python module will have a direct access to the globals in the module which imports it or vice versa.

Below is my code:

x.py

import y

def f():
    global x
    x = 6
    print(x)

def main():
    global x
    x = 3
    print(x)
    f()
    y.g()

if __name__ == '__main__':
    main()

y.py

def g():
    global x
    x += 1
    print(x)

Below is the traceback:

3
6


   Traceback (most recent call last):
      File "C:\Users\abc\Desktop\x.py", line 16, in <module>
        main()
      File "C:\Users\abc\Desktop\x.py", line 13, in main
        y.g()
      File "C:\Users\abc\Desktop\y.py", line 3, in g
        x += 1
    NameError: name 'x' is not defined

Upvotes: 0

Views: 42

Answers (1)

fjarri
fjarri

Reputation: 9726

"Global variable" in Python means global relative to the module. You have a x.x variable, which is defined and a y.x variable, which is undefined and produces the error when you try to retrieve its contents. If you want access to another module's globals, you will have to import that module explicitly (although messing with another module's globals is almost always a bad practice).

For reference, see e.g. Python docs:

If the global statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace. Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and the builtins namespace, the namespace of the module builtins. The global namespace is searched first. If the name is not found there, the builtins namespace is searched. The global statement must precede all uses of the name.

Upvotes: 1

Related Questions