You've been writing some great Python code. You've even created a handful of really useful functions that you find yourself using over and over. Now you're starting a new project, and you need those same functions again.
Your first instinct might be to copy and paste them from your old file into your new one. But a voice in the back of your head tells you, "This feels wrong." And you're right. Copy-pasting code is inefficient and a nightmare to maintain.
So, how do you access the functions you wrote in my_tools.py from your new main_project.py script? The answer is one of Python's most elegant features: modules.
The "Aha!" Moment: Every .py File is a Module
Here’s the simple but profound secret: any file you save with a .py extension is a module that you can import.
You've already been using modules like pandas or requests. The import keyword isn't just for third-party libraries; it works exactly the same way for your own files. Understanding this is the key to organizing any project, big or small.
The Step-by-Step Guide to Creating and Importing Your Own Module
Let's walk through a practical example. For this to work, both files must be saved in the same folder.
Step 1: Create Your "Tools" Module
First, create a new file named my_tools.py. This file will hold our reusable functions. Let's add a couple of simple ones.
# FILE: my_tools.py
def say_hello(name):
"""A simple function that returns a greeting."""
return f"Hello, {name}!"
def calculate_vat(amount, rate=0.13):
"""Calculates the Value Added Tax for a given amount."""
return amount * rate
Save this file. You now have your very own custom module.
Step 2: Create Your "Main" Script
Next, in the same folder, create another file named main.py. This is where the main logic of our new project will live.
Step 3: Import Your Module
Inside main.py, the first thing we'll do is import our tools module. The module name is the file name, without the .py.
# FILE: main.py
import my_tools
Step 4: Use Your Imported Functions
Now that you've imported my_tools, you can access any function inside it using dot notation (module_name.function_name).
# FILE: main.py
import my_tools
# Use the say_hello function from the my_tools module
greeting = my_tools.say_hello("World")
print(greeting) # Output: Hello, World!
# Use the calculate_vat function
invoice_total = 1000
vat_amount = my_tools.calculate_vat(invoice_total)
print(f"The VAT on {invoice_total} is: {vat_amount}") # Output: The VAT on 1000 is: 130.0
It's that simple! You've successfully separated your reusable "tool" code from your main application logic.
Alternative Import Methods (and a Word of Caution)
There are other ways to import, but you should know the pros and cons.
from ... import ...: This imports a specific function directly.Pythonfrom my_tools import say_hello # Now you can call it directly without the module name greeting = say_hello("Alice")Use case: Good when you only need one or two functions from a large module.
from ... import *: This imports everything from the module.Pythonfrom my_tools import * greeting = say_hello("Bob") vat = calculate_vat(500)Warning: While this seems convenient, it's generally considered bad practice. It "pollutes your namespace" by dumping all the functions from the module into your current script, and you can easily have name collisions if two modules have a function with the same name. Avoid this unless you have a very good reason.
Frequently Asked Questions (FAQs)
1. Do the files have to be in the same folder?
For beginners, yes, keeping them in the same folder is the simplest and most reliable way. Python automatically looks for modules in the current directory. (For advanced projects, you can organize them into packages or modify the Python path).
2. What if my filename has a hyphen, like my-tools.py?
This will not work. Module filenames must be valid Python identifiers, which means they can contain letters, numbers, and underscores, but cannot start with a number or contain hyphens. my_tools.py is good; my-tools.py is bad.
3. What is that __pycache__ folder that sometimes appears?
When you import a module, Python compiles it into a faster "bytecode" version and saves it in a __pycache__ folder. This makes imports quicker the next time you run your program. You can safely ignore or delete this folder; Python will regenerate it if needed.
Conclusion: From Scripts to Projects
You've just taken a monumental step from being a scripter to being a software developer. Understanding how to create and import your own modules is the foundation of writing clean, organized, and scalable code.
modules help you organize your classes and functions into logical, reusable files. You can now build your own library of tools that you can share across all your future projects, saving you time and making your code infinitely more maintainable. For more details, the

No comments:
Post a Comment