Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to import variables from another file in Python?

  • Last Updated : 03 Mar, 2021

When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simple import <library_name>. For example, math library. If we want to use the pi variable we use import math and then math.pi.

To import variables from another file, we have to import that file from the current program. This will provide access to all the methods and variables available in that file.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

The import statement

We can use any Python source file as a module by executing an import statement in some other Python source file. When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module.



The from import Statement

Python’s from statement lets you import specific attributes from a module. 

Note: For more information, refer Python Modules

Different approaches to import variables from other file

  • import <file_name> and then use <file_name>.<variable_name> to access variable
  • from <file_name> import <variable_names> and use variables
  • from <file_name> import * and then use variables directly.

Example:

Suppose we have a file named “swaps.py”. We have to import the x and y variable from this file in another file named “calval.py”. 

Python3




# swaps.py file from which variables to be imported
x = 23
y = 30
  
def swapVal(x, y):
  x,y = y,x
  return x, y

Now create a second python file to call the variable from the above code:

Python3




# calval.py file where to import variables
# import swaps.py file from which variables 
# to be imported
# swaps.py and calval.py files should be in 
# same directory.
import swaps
  
# Import x and y variables using 
# file_name.variable_name notation
new_x = swaps.x
new_y = swaps.y
  
print("x value: ", new_x, "y value:", new_y)
  
# Similarly, import swapVal method from swaps file
x , y = swaps.swapVal(new_x,new_y)
  
print("x value: ", x, "y value:", y)

Output:

x value:  23 y value: 30
x value:  30 y value: 23



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!