g2142007 g2142007
g2142007 g2142007

Reputation: 17

How to reuse python code in one file from a different file

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

Answers (4)

User051209
User051209

Reputation: 2513

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

Upvotes: 0

Mark Maxwell
Mark Maxwell

Reputation: 76

  1. Ensure that the two files are in the same directory.

If this is the case, you can directly import


from filename import variablename/class/function

in your case:


from code1 import a

Upvotes: 1

Minura Punchihewa
Minura Punchihewa

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

svfat
svfat

Reputation: 3363

This lesson is good to understand imports in python: https://realpython.com/python-import/

Upvotes: 1

Related Questions