The code showed below is based on the fact that files code1.py
and code2.py
are in the same directory.
Solution 1
In this code I have changed only your import
instruction in code2.py
:
from code1 import a
b = a + 1
print(b)
Solution 2
In this solution I don't have changed your import
instruction in the file code2.py
, but I have used the module name (code1
) to refer to a
variable. In this case it is used the access notation moduleName.variableName
.
So the file code2.py
becomes:
import code1
b = code1.a + 1
print(b)
This means that in this case code1.py
is used as a Python module and not as a script (the difference between script and module could be the topic of an other question).
Python namespace
In Python terminology the moduleName
is the namespace defined by the module. By the namespace you can access to the objects content inside the module by the syntax namespace.object
.
The interpreter creates a global namespace for any module that your program loads with the import statement.
So in the code showed by the question the variable a
is part of the namespace code1
.
Link useful about the topic of the post
- About namespace useful this link of realpython.
- For an example about access to an attribute of a class defined in an other module see this post
- Here there is an example for access to a dictionary defined in an other module