How to Create a Module in Python?


A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable name. For instance, use your favorite text editor to create a file called fibo.py in your project directory.

A module can define functions, classes, and variables. A module can also include runnable code. In this article, we will go over how to create and import modules in Python.

Writing modules

Writing Python modules is very easy. To create a module just save the code you want in a file with the file extension .py:

A module can be created by creating a hello.py file.

# hello.py def hello_world(): print("Hello World!")
Code language: PHP (php)

Importing Modules

Before using a module, it must first be imported. To import a module type import followed by the name of the module:

import example_module
Code language: JavaScript (javascript)

imports the entire module and makes it available for use later in your program. If you only want certain functions or variables from a module, list their names after the import keyword:

from example_module import example_function, example_variable
Code language: JavaScript (javascript)

The functions in a module can be used by importing the module.

Your own modules must be in the same directory as the import file.

You can alternatively place them in Python’s lib directory with pre-included modules, but it’s not recommended.

$ python >>> import hello >>> hello.hello_world() => "Hello World!"
Code language: JavaScript (javascript)

If the module is inside a directory and needs to be detected by python, the directory should contain a file named __init__.py

That concludes our overview of how to create modules in Python. As you can see, they are relatively simple to put together and can be an extremely useful tool when coding larger projects composed of multiple files. Modules can help keep your code organized and prevent namespace issues from arising. Stay tuned for more blogs on interesting topics in computer science!


Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts