Creating Custom Modules

2 min read ·

Custom modules allow you to organize your own code into separate files and reuse it across multiple programs.

Creating .py File

A module is simply a Python file with .py extension.
Example file name: my_module.py

Writing Functions and Classes

Inside the module, you can define functions, variables, and classes.

Note

A module can contain any valid Python code, including functions, classes, and variables.


Importing Custom Modules

To use your module, it should be in the same directory or accessible via Python path.

Using Alias

You can import your module with a shorter name.

Import Specific Items


Reusing Modules

Once created, a module can be reused in multiple files.
Example:
  • my_module.py → contains logic
  • app1.py → uses module
  • app2.py → also uses same module
This avoids rewriting the same code again.

Pro Tip

Keep modules focused on a single responsibility to make them easier to reuse and maintain.


Important Points

  • File name should be valid Python identifier
  • Avoid naming conflicts with built-in modules
  • Keep module in correct directory

Caution

If Python cannot find your module, check the file location or module search path.


Exercise

  • Create a module named utils.py
  • Add a function to calculate square
  • Add a class with a method to print a message
Import it in another file and use both function and class.