Call Python function from another Python file

call Python function from another file in Python

In this article, you will know how to call a function of other Python files using the import keyword. Also, you will get to know how to import a single class, not the whole file.

Building software needs a network of codes and files of codes in a systematic way. The network can be created by calling functions from one file to another.

Python has a simple way to use the functions of other Python files. Importing that file using import keyword and aliasing it is very simple. For example, the same directory has two Python file  and having their functions. Then how you can use functions in, that will see in the code below.

def intro():
    return 'This is baseFile'

def secFun():
    return 'This is second function'

import baseFile as b


This is baseFile


Import only class you want

In some cases, you import the whole file but you need some of the classes functions only. There is no need to import the whole file and just import that specific class only. So if you want to import any specific class then you can follow this way of import.

class First:
    def firstFun():
        return 'This is First class' 
class Second:
    def secFun():
        return 'This is Second class'

from baseFile import Second as s


This is Second class

Also, read:


Import all classes, functions and variables using *

* is a wild card symbol that is used to import all classes, functions and variables present in the python file. In the various field, it is used to search all the content present in the table of file.

from baseFile import *

I hope you got the idea of using functions, functions of a class from other Python files.


One response to “Call Python function from another Python file”

  1. G Ram Prasad says:

    Your presentation on how to use a python file from another python file is very simple and comprehensive.Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *