Free Web Development Online Tutorials, Learn to Code
Python modules and packages example, Python tutorial for beginners, Python Web Development Guide

Python Modules and Packages

What is Modules in Python?

A Module is like a code library in python, module allows to logically organize code in any Python application.

For example, think of a situation when you want to create an application for school, there you may need to create a module for student and another module for teacher.

Actually module is a python file, where you want to write a group of functionalities, object definition etc. so that can easy to use and maintain the code base for future enhancement.

So, for school application we can create two modules and

Let’s look at the following picture to understand python packages and modules

python packages modules

As you can see we have created two modules in school package in above application, we have also used a base class (People) to explain how inheritance works in python, but before we explain more about how to write function in each module an create a new instance of any class to access the function, let’s understand the package in python.

How to Create Package in Python

To create a package in python, you need to create a folder, and then add all relevant files in that folder those need to be a part of that package, finally add a file in that folder. file can be kept empty

    class __init__(object):
    """description of class"""

So in above picture we have demonstrated a project structure with module and package concept in python.

Let's try to create same structure in your local environment!

Here are the steps

  • Create a folder called "Student"
  • Create a file in that folder
  • Create a python file named ""
  • Inside the "" file create Student class as shown below

Here in Student class we have created some properties with and without default values and a method to print the person name.

class Student(object):
    def __init__(self, fname, lname):
        self.first_name = fname
        self.last_name = lname

    def personName(self):
        print(self.first_name, self.last_name)

Now in Main class we create a new instance of Student class and access the "personName" method, but before that we need to import the Student class.
So the syntax is from PackageName.ModuleName Import ClassName

from School.Student import Student

class Main(object):
    student =  Student();  

Here in above example, class name and module name are the same, but you can have different class name, also you can add multiple classes in the same module.

Modules and Packages in Python

Modules Modules
Python programming examples | Join Python Course