But as you get more advanced, and your code gets more complex, you need to learn to use multiple files.
What Exactly is a Python Module?
A Python module is a Python file that contains classes, methods, or variables that you’d like to include in your application.
A common practice that you’ll observe among advanced Python applications is reusable functions or classes combined in a file, and then imported in other parts of the program.
This is referred to as a Python module. This module can then be imported and the variables and functions can be reused multiple times without declaring or creating them every time.
How to Create a Python Module?
It’s simple, but we’ll break it down into small chunks for you to understand it and be able to apply it in real-world scenarios.
1. Create a File Containing a Method
We’ll first create a basic method that adds two numbers which it accepts as parameters.
name = "AskPython" def add(num1, num2): return num1 + num2
This is our module. The above code is simply a method that returns the sum of the two numbers that are passed to it. Save the above code as
adder.py and we’ll move on to the next step.
2. Create the Main File to Import the Module
Our next step is to import custom python modules in our program. Now, this is exactly the same as importing any other module.
The only difference is that the module file is locally located instead of being in the system path.
import adder nums = adder.add(5, 10) print(nums)
In the above example, I’ve imported our “adder” file. You don’t need to add the “.py” extension while importing.
3. Importing Only One Function
Suppose in our module, we had multiple functions performing multiple tasks. But in the program that we are importing the module, we needed only one of those functions. Importing the entire module would be unnecessary.
In this case, we can make use of
from adder import add nums = add(5, 10) print(nums)
As you can see, since we’re importing a specific function, Python allows us to use the function as if it was native to the file without having to reference it with the module name.
4. Using Variables From Our Module
You might have noticed the two variables in our module. We added those to demonstrate how variables can be directly imported from the module with their values intact.
import adder nums = adder.add(5, 10) print(nums) print(adder.name)
Importing Modules From Different Directory
You do not need to store the module in the same folder as your main file. That would become very inconvenient if there are a lot of files.
Also in case you’re importing a module to a different program, it will be difficult to use the module.
Instead, you can organize modules in folders, and still import them in the same manner as before. We’ll just have to make a small change to the import statement and everything else will run fine.
There are multiple ways we can import modules in our program which are not located in the root directory. Let’s start with the easy ones.
1. Import by Specifying Folder Name
The dot notation or
from..import that we used above can be used to import modules that are located within a directory. Let’s place our “adder.py” module in a directory named modules.
import modules.adder as adder nums = adder.add(5, 10) print(nums) print(adder.name)
In this example, we renamed our module name from “modules.adder” to “adder” using as.
The reason for that is without renaming, we’ll have to specify “modules.adder.add(5,10)” and so on every time we need to call a function from the module.
We do not need to rename a module in the
import statement. We can also create a variable later in the program that holds the name of the module and use the variable to call functions within the module.
adder = modules.adder
This will work too, but declaring the new name right at the start of the program improves code readability making it easier for the next programmer who works on your piece of code.
Another way is to use from..import. This saves us from renaming the modules for use in the program. The only change I’ll need to make to my import command is to use from modules import adder
from modules import adder nums = adder.add(5, 10) print(nums) print(adder.name)
2. Append The Path to sys.path
When importing modules, Python starts by looking into the predefined paths first to find a module that matches the name. The first directory it looks into is the current directory, after which it moves to the other listed directories.
Let’s print out the sys.path and see what paths Python is looking into.
import sys print(sys.path)
The above output is generated on a Linux computer. You will get a different list of paths if you’re using a Windows computer.
Since the sys.path is a Python list, we can append paths to it.
import sys sys.path.append("modules") import adder nums = adder.add(5, 10) print(nums) print(adder.name)
We imported the sys module and appended our “modules” directory to it. So any time you need to import a module in the modules directory within this program, you can simply specify the name and you should be good to start working.
3. Making a Module Available System-Wide
We printed out the sys.path in the above example. We know that Python will look into those directories by default irrespective of where your code is placed.
If we move our module to one of those directories, you will easily have access to the module from any program you create on your computer in the future.
Do note that when porting the program to a different system, you will need the module to be copied along. So for program-specific modules, it’s best to organize them in folders within the parent directory and import from there.
You should now be able to create your custom modules in Python and write multi-file programs. Remember, having code organized in multiple files with the use of classes is a far better option for code reusability.
Many functions that you need now, could be useful in a future application too and these individual modules that you’ve created would just need to be imported saving you hours of work in case of advanced applications.