How to import variables from another file in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To import variables from another file in Python, you can use the import statement.

Assuming file1.py contains variables x and y, you can access them in file2.py as follows:

import file1

print(file1.x)  # prints the value of variable x defined in file1.py
print(file1.y)  # prints the value of variable y defined in file1.py

In this example, we use the import statement to import the file1 module, which contains the variables x and y. We can then access these variables using the dot notation file1.x and file1.y.

Alternatively, you can use the from keyword to import specific variables from file1.py:

from file1 import x, y

print(x)  # prints the value of variable x defined in file1.py
print(y)  # prints the value of variable y defined in file1.py

In this example, we use the from keyword to import only the x and y variables from file1.py. We can then access these variables directly without using the file1. prefix.

Tags:

related content