Python Modules: How to Import and Reuse Code

Python Modules: How to Import and Reuse Code
Photo: Wikimedia Commons

Python modules let you save your code in separate files and use it anywhere you want. If you find yourself copying the same code into three different places, you need a module. It makes your work cleaner, speeds up your projects, and keeps your files small.

A module is just a regular file filled with code that ends in dot py. You can bring that code into your main file with one simple word: import. This means you write a helpful tool once, and every project you make can use it immediately.

What Is a Python Module and Why Use One?

Think of a module like a plastic tool container in your garage. Instead of leaving every hammer, screwdriver, and tape measure spread out on your kitchen table, you put them in a box. When you need to fix a door, you grab the box. Python works the same way.

When your main file reaches 500 lines of code, finding errors gets hard. Reading through it feels slow. By moving math helpers or text checkers into separate files, your main file stays neat. I spent two hours last week tracking down a simple typo just because my main script was way too long. Splitting code into modules fixes that headache.

You also save time when you build new apps. If you write a great tool to format prices or handle dates, you do not want to write it again next month. You just load the file you already made. If you want to learn more about structuring code, check out our guide on Python Classes: How to Build Your Own Objects to see how tools fit together.

Here is what a tiny custom file called helper dot py looks like:

# File name: helper.py

def greet_user(name):
    return f"Hello, {name}! Welcome back."

def add_tax(price):
    return price * 1.05

That is all it takes. There is no special magic setup. Any normal code file can act as a module for another script.

How to Import Built in Python Modules

Python comes with dozens of built in files ready for you to use. People call this the standard library, but you can think of it as free extra features. You do not need to download anything new. They sit on your computer right now waiting for you.

To use a built in file, put the word import at the very top of your script. Then type the name of the tool you want. For example, if you need to generate random numbers for a game, you use the random tool.

import random

dice_roll = random.randint(1, 6)
print(f"You rolled a {dice_roll}")

Notice how we wrote random dot randint. The first word is the name of the file. The second word is the function inside that file. This tells Python exactly where to look so it does not get confused.

Another famous built in tool is math. If you need square roots or rounding functions, math has them ready. Here is a quick example of math in action:

import math

number = 16
result = math.sqrt(number)
print(f"The square root of {number} is {result}")

Using built in tools keeps you from rebuilding wheels. Need to track time? Use the time tool. Need to pick a random item from a list of users? Use random dot choice. It saves you dozens of lines of extra typing.

How do you create and import your own Python module?

Making your own file to import is super easy. First, open your code editor and create a new file. Name it my_tools dot py. Make sure it stays in the exact same folder as your main script, or Python will not find it.

Inside my_tools dot py, add a function that calculates a discount for a store buyer:

# File name: my_tools.py

def calculate_discount(total, percent):
    discount_amount = total * (percent / 100)
    return total - discount_amount

Now, save that file. Open a second file in the same folder and name it main dot py. Inside main dot py, you bring in your custom tool just like a built in one:

# File name: main.py
import my_tools

original_price = 100
final_price = my_tools.calculate_discount(original_price, 20)
print(f"Your total after discount is {final_price}")

When you run main dot py, Python looks inside the folder, opens my_tools dot py, and runs the function. If you want to dive deeper into custom logic, read our tutorial on Python coding foundations for beginners to strengthen your basic skills.

What if you only want one single function from that file? You can grab just what you need using the from keyword. This lets you skip typing the file name every time you use the function.

from my_tools import calculate_discount

# Now you do not need to write my_tools.first!
final_price = calculate_discount(50, 10)
print(final_price)

This approach keeps your lines short. But be careful not to import two functions with the exact same name from different places, or one will overwrite the other!

Using Short Names and Shortcuts with Import

Sometimes a module name feels too long to type ten times in a row. Python gives you a neat trick to rename things on the fly using the as keyword. This creates a short nickname for your script.

People who work with data do this constantly. For example, there is a famous tool for math named datetime. Typing datetime dot datetime over and over gets old fast. You can rename it to something shorter like dt.

import datetime as dt

current_time = dt.datetime.now()
print(f"Today is {current_time}")

You can also do this with individual functions. If a function name is very long, shorten it right at the import line:

from my_tools import calculate_discount as get_sale

price = get_sale(200, 15)
print(price)

This makes your code look clean and quick to read. Just make sure the nickname still makes sense to anyone else reading your script later on. A bad name like x or z will confuse your future self!

Where Does Python Look for Imported Files?

When you write an import statement, Python does not search your whole hard drive. It looks in a few specific spots in a set order. Understanding this list stops those annoying module not found errors before they start.

First, Python checks the folder where your active script lives. If your main file and custom module share a folder, it finds it instantly. Second, it checks built in tools like math or random. Third, it checks external libraries you installed using pip.

You can see this search path yourself by importing the sys module and printing sys dot path:

import sys

for location in sys.path:
    print(location)

If you get a ModuleNotFoundError, it means your file is not in one of those folders. The fastest fix is moving your module into the exact same folder as the script calling it.

Never name your custom file the same name as a built in tool! If you name your file random dot py and then try to import random, Python gets confused. It loads your blank file instead of the built in tool, and your code breaks with strange errors.

How to Organize Code into Packages

As your apps grow, having thirty separate files floating in one folder gets messy. You need a way to group related files together. In Python, a folder containing multiple code files is called a package.

Creating a package is super simple. Make a regular folder on your computer and name it store_tools. Inside that folder, create two files: pricing dot py and shipping dot py.

Here is what the file list looks like on your computer:

my_project/
│
├── main.py
└── store_tools/
    ├── pricing.py
    └── shipping.py

To use code from inside that folder in your main dot py, use dot notation. You name the folder first, then a dot, then the file name:

from store_tools import pricing

total = pricing.add_tax(50)
print(total)

You can also jump straight to a specific function inside a nested file:

from store_tools.shipping import calculate_postage

cost = calculate_postage(weight=3)
print(cost)

This folder setup keeps big apps easy to navigate. You can put all database files in one folder, all webpage views in another folder, and all math scripts in a third folder. For more tips on organizing your project files, check out Python Classes: How to Build Your Own Objects to learn smart design patterns.

Installing Third Party Modules with Pip

The built in tools in Python are great, but the real power of Python comes from millions of free tools written by developers around the world. These are called third party packages.

You download these tools using a command line tool called pip. It comes installed with Python automatically. You open your terminal or command prompt and type pip install followed by the package name.

For instance, if you want to grab information from websites easily, you can install the famous requests tool:

pip install requests

Once the installation finishes, you import it into your script just like a built in tool!

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

That simple script connects across the internet and gets a response in two lines. Learning to use third party files opens up endless possibilities. You can make web apps, build games, read Excel files, or control smart home lights with minimal code.

If you ever want to check out more ways to grow your programming setup, visit our tech learning hub for Python projects for clear guides on real world scripts.

Best Practices for Clean Module Imports

Writing clean code means following standard rules so other developers can read your work easily. Here are three simple rules every programmer follows when importing files.

First, put all your import lines at the very top of your file. Do not hide an import line inside the middle of a function or halfway down the script. Anyone opening your file should see what tools it relies on in two seconds.

Second, group your imports in a clear order with a space between groups:

  • Group 1: Standard built in modules like random, math, or sys.
  • Group 2: Installed third party modules like requests.
  • Group 3: Your own custom local files you created.

Here is a good example of organized imports:

import random
import math

import requests

import my_tools

Third, avoid wildcards. Writing from math import * grabs every single tool inside math. This sounds nice, but it fills your script with hidden names. It makes your code harder to read because no one knows where specific functions came from!

Practical Tips You Can Use Today

Ready to clean up your own scripts? Here are three easy actions you can take right now to practice using modules:

  • Split a large file: Find your longest script. Pick three helper functions and move them into a new file named utils dot py in the same folder. Import them into your main script.
  • Try the random tool: Open a fresh Python file, import random, and build a quick coin flipper using random dot choice with heads and tails.
  • Check built in files: Open your terminal and type python to open the interactive shell. Type import math then dir(math) to see every function hidden inside math.

How are you planning to split up your next project? Start small with one helper file, and you will see how much easier programming becomes!

Post a Comment