Python – Call function from another file
Given a Python file, we need to call a function in it defined in any other Python file.
Suppose there is a file test.py which contains the definition of the function displayText().
print( “Geeks 4 Geeks!”)
We need to call the function displayText() in any other Python file such that wherever we call displayText() function displays text present in it. This can be done using Python modules.
- Create a Python file containing the required functions.
- Create another Python file and import the previous Python file into it.
- Call the functions defined in the imported file.
The above approach has been used in the below examples:
Example 1: A Python file test.py is created and it contains the displayText() function.
Now another Python file is created which calls the displayText() function defined in test.py.
Geeks 4 Geeks!
In the above program, all the functions defined in test.py file is imported then a functions is called.
Example 2: A Python file calc.py is created containing addNumbers(), subractNumbers(), multiplyNumbers(), divideNumbers() and modulusNumbers().
The functions defined in calc.py is called in another Python file.
In the above program, all the functions defined in calc.py are not imported.
To import all the functions defined in a Python file:
from file import *
To import only required functions defined in a Python file:
from file import func1, func2, func3
The below Python files test.py and calc.py are created having various function definitions.
Both files are imported into an another Python file named file.py.
Sum is 31 Difference is 19 Product is 150 Division is 4.166666666666667 Remainder is 1 Geeks 4 Geeks!
In the above program, functions defined in test.py and calc.py are called in a different file which is file.py.
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