Reputation: 17
My question is very simple. I have a piece of code that I want to reuse, but I don't want to copy it every time I use it. Is there any way I can import it and run it in my main file?
For example, in file code1.py
:
a=1
I want to run in code2.py
:
import code1
b=a+1
print(b)
The output says a
is not defined. I don't know where I got it wrong. I am a beginner in Python, so this will help me a lot in the future, thanks.
Upvotes: 0
Views: 955
Reputation: 2513
The code showed below is based on the fact that files code1.py
and code2.py
are in the same directory.
In this code I have changed only your import
instruction in code2.py
:
from code1 import a
b = a + 1
print(b)
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).
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
Upvotes: 0
Reputation: 76
If this is the case, you can directly import
from filename import variablename/class/function
in your case:
from code1 import a
Upvotes: 1
Reputation: 2025
You will need to import the variable from the your Python module to use it.
from code1 import a
The import statement will differ slightly if your modules are not at the same level.
Upvotes: 0
Reputation: 3363
This lesson is good to understand imports in python: https://realpython.com/python-import/
Upvotes: 1