Call Python function from another Python file

Hello friends, today we will learn how to call a function of a different Python file. In Python, you can use the functions of other Python files by using the import keyword. I will also tell you how you can import a single function instead of the entire file.
Call Python function from another Python file
Let’s take two Python files baseFile.py
and callerFile.py
. (Both are in the same directory)
You can check it: Call Python function from a different directory’s Python file
‘baseFile.py
def intro(): return 'This is baseFile' def secFun(): return 'This is second function'
callerFile.py
import baseFile as b print(b.intro())
Output:
This is baseFile
In my baseFile.py
I have created two functions intro
and secFun
. I can use these functions from another Python file as well, which will help me keep my code clean and understandable. In the callerFile.py
, I have imported the baseFile
with an alias b. This enabled me to create an object for baseFile.py
. Now I can use methods baseFile.py
by calling them in the other file.
Another way to import a file is by using a * in the import statement. * is a wild card symbol that is used to import all classes, functions, and variables present in the Python file.
from baseFile import *
Here, the import statement is different from the previous one but they both do the same thing.
Import only the function you want
In some cases, you want a specific function. There is no need to import the whole file, just import the specific function alone. For example, I want to use the secFun
only, while importing I will import the secFun
only.
callerFile.py
from baseFile import secFun print(secFun())
Output:
This is Second class
I hope you got the idea of using functions, functions of a class from other Python files.
Your presentation on how to use a python file from another python file is very simple and comprehensive.Thank you.