Python is a flexible and comprehendible language and there are many examples to prove the prior statement. You can have sperate and independent files and still be able to use and include them in your application. How does this is an advantage? Suppose you have worked on a login page and saved it in a file. You can save your time by not repeatedly creating a login page for each application you develop. You can just add the functionality of that file. Importing a function from another file in python extends the reach of the software without much of an effort.
In this article, we will cover how to import components like functions and classes from another file in python. Python has different frameworks and open source applications like Django, flask, and Jupyter notebook.
We will use Jupyter Notebook in our examples, but you are free to implement it in any other framework.
In most applications, there is a directory system which is installed while creating a project. You don’t need to add a path if you have the file in the project. However, in Jupyter notebook, we need to fist add the path from which Jupyter notebook can read the path.
There are 3 simple steps you can go ahead and skip you don’t need to add the path.
Step 1: search environment variable in your windows panel.
Step 2: Click on new.
Step 3: add the path and click ok
View the path in your notebook to make sure the path has been successfully added.
To add the external file, go ahead and save it in the directory you added above.
To import the file in your application, type in the following command.
you can add the file and use the functions by the file name.
the definition of this file is in another file named Funcmodules.py.
You can import a few functions in your application to prevent from importing things you don’t need.
from Funcmodule import myfunction
Similarly, you can import the class from another file into your application.
Suppose this is the class defined in another file outside of your application.
#my_file.py class myClass: def __init__(self,val): self.val=val def func(self): return self.val
#import the my_file.py in your application. from my_file import myClass newClass = myClass(8) value = newClass.func () print(value)
Importing external files in your application is a good practice to reuse code and save time. Accessing functions, classes and other components from your file has proven to be time-efficient, optimal, and leave room for creativity without getting caught in unwanted aspects.