In a file a.py
I have the following code:
# a.py
def test():
global i
print(f'The number is {i}')
So, in a file b.py
I imported a.py
:
# b.py
from a import *
i = 22
test()
When I run this code I get the following error:
NameError: name 'i' is not defined
I thought this would work, once the function was imported, and, object i was defined in b.py. How do I resolve this?
A few things to note.
First, import * is not encouraged as it brings a lot of modules over that you might have no interest in. It is why you will often see particular imports from modules.
Second, a globally declared variable is global only in the context of the module a. When you import *, you have imported a variable called i from a, referenced in code as a.i. To get this to work, you can alter your b.py code to the following
import a
a.i = 22
a.test()
The issue with your code is you are declaring i in module b which module a has no capability of referencing - global is only global within a module. So by declaring a.i = 22, you are telling module a that its global i value is now 22.
I would say better way to approach this would be to make your function take in an argument i and have no need to reference a specific within the module itself, but I don't know your use case. I will add the code below regardless!
a.py
def test(i):
print(f'The number is {i}')
b.py
from a import test
i = 22
test(i)
Cheers!