How to import variables from another file in Python?
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.
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.
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”.
Now create a second python file to call the variable from the above code:
x value: 23 y value: 30 x value: 30 y value: 23