CodingNic

Modules, Packages, and Virtual Environments

Creating Your Own Modules

Modules, Packages, and Virtual Environments 28 min read

Creating Your Own Modules

Creating Your Own Modules

Python includes many built-in modules.

But you can also create your own modules to organize your code.

This is useful when projects become bigger.

What Is Your Own Module?

Your own module is simply a .py file you create that stores reusable code.

It can contain:

  • functions
  • variables
  • classes

Why Create Your Own Modules?

They help you:

  • reuse code
  • keep files smaller
  • organize projects
  • separate responsibilities

Example Project

Instead of one large file:

text
main.py

Use:

text
main.py
helpers.py

Create a Module

Create a file named:

text
helpers.py

Add:

python
def greet(name):
    print("Hello", name)

def add(a, b):
    return a + b

Use the Module

Create:

text
main.py

Add:

python
import helpers

helpers.greet("Tom")
print(helpers.add(2, 3))

Output

text
Hello Tom
5

Import Specific Functions

python
from helpers import greet

greet("Sara")

Output

text
Hello Sara

Module with Variables

python
# settings.py
theme = "dark"
language = "English"

Use it:

python
import settings

print(settings.theme)

Output

text
dark

Module with Classes

python
# users.py
class User:
    def hello(self):
        print("Welcome")

Use it:

python
from users import User

u = User()
u.hello()

Output

text
Welcome

Common Beginner Errors

Wrong File Name

The file name is the module name.

Typing Code Outside the File

Make sure code is saved inside the module file.

Circular Imports

Do not make two files import each other yet.

Code Along

Create math_tools.py with:

  • double(n)
  • square(n)

Use both in main.py.

Mini Challenge

Create:

text
messages.py

Add:

  • hello()
  • bye()

Import both functions and run them.

Expected output:

text
Hello
Goodbye

Real World Use Case

Real apps use custom modules for users, payments, reports, settings, database tools, and utilities.

Quiz

  1. What is a custom module?
  2. Why create your own modules?
  3. Can modules store classes?
  4. What is the module name if the file is tools.py?

Assignment

Create a module with two functions and one variable, then import and use all three.

Summary

You learned how to create your own Python modules and organize reusable code into separate files.