Skip to content

Python Modules

Modules: Libraries of Code

A module is a file containing a set of functions and variables you want to include in your application.

Why use Modules?

  1. Don't Reinvent the Wheel: Use code written by experts for complex tasks (like math, networking, or AI).
  2. Modularity: Keep your project files small and organized by splitting them into different files.

How it works?

  • Importing: You "bring in" the module into your current file.
  • Built-in Modules: Modules that come pre-installed with the language.
  • External Modules: Modules created by other developers that you can download.

The Lego Analogy

Modules are like Lego sets. You can build your own pieces, but you can also use ready-made kits to build complex things faster!

Create a Module

To create a module just save the code you want in a file with the file extension .py:

mymodule.py

def greeting(name):
  print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

import mymodule

mymodule.greeting("Vishnu")

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

import mymodule as mx

mx.greeting("Vishnu")

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

import platform

x = platform.system()
print(x) # Windows / Linux

Using from

You can choose to import only parts from a module, by using the from keyword.

from mymodule import greeting