Lesson 10.4: Organizing Your Code
What you will learn:
- How to create your own Python modules
- What
__name__ == "__main__"means and why it matters - How to structure a Python project
- Best practices for organizing code across files
1. Creating Your Own Modules
Any Python file can be used as a module. If you save functions in a .py file, you can import and use them in other files. This is one of the most powerful ways to organize your code.
Step 1: Create a module file (helpers.py)
# helpers.py - a custom module with useful functions def greet(name): """Return a greeting message.""" return f"Hello, {name}! Welcome!" def calculate_average(numbers): """Calculate the average of a list of numbers.""" if len(numbers) == 0: return 0 return sum(numbers) / len(numbers) def is_even(number): """Check if a number is even.""" return number % 2 == 0
Step 2: Use the module in another file (main.py)
# main.py - uses functions from helpers.py import helpers # Use functions from the helpers module message = helpers.greet("Alice") print(message) scores = [85, 92, 78, 95, 88] avg = helpers.calculate_average(scores) print(f"Average score: {avg}") print(helpers.is_even(7)) # False print(helpers.is_even(4)) # True
Average score: 87.6
False
True
2. Understanding __name__ == "__main__"
You will often see this pattern in Python files. It controls what code runs when a file is executed directly versus when it is imported as a module.
__name__ is set to "__main__". When a file is imported as a module, __name__ is set to the module's name.
Example: math_tools.py
# math_tools.py def double(n): return n * 2 def triple(n): return n * 3 # This code ONLY runs when math_tools.py is run directly # It does NOT run when math_tools is imported if __name__ == "__main__": print("Testing math_tools...") print(double(5)) # 10 print(triple(5)) # 15 print("All tests passed!")
When Run Directly vs. Imported
# Running directly: python math_tools.py # Output: # Testing math_tools... # 10 # 15 # All tests passed! # Importing in another file: import math_tools # No output! The test code doesn't run. # But the functions are available: print(math_tools.double(8)) # 16
This pattern is incredibly useful because it lets you:
- Test your module by running it directly
- Import it into other files without running the test code
- Include example usage that does not interfere with imports
3. Project Structure
As your programs grow, organizing code into multiple files becomes essential. Here is a typical project structure:
A Mini Project Example
# data_processing.py def clean_name(name): """Remove extra spaces and capitalize properly.""" return name.strip().title() def validate_age(age): """Check if age is a valid positive number.""" return isinstance(age, int) and age > 0 def format_record(name, age): """Create a formatted string for a person's record.""" return f"{clean_name(name)} (age {age})"
# main.py from data_processing import clean_name, validate_age, format_record # Process a list of people people = [ (" alice ", 30), ("BOB", 25), (" charlie johnson ", 35) ] for name, age in people: if validate_age(age): print(format_record(name, age))
Bob (age 25)
Charlie Johnson (age 35)
4. Best Practices
Follow these guidelines to keep your code organized and maintainable:
Do: Group Related Functions Together
# string_utils.py - all string-related helpers def reverse_string(text): return text[::-1] def count_vowels(text): return sum(1 for c in text.lower() if c in "aeiou") def is_palindrome(text): clean = text.lower().replace(" ", "") return clean == clean[::-1]
- One purpose per module: Each file should have a clear, focused purpose
- Use descriptive file names:
data_processing.pyis better thanstuff.py - Add docstrings: Document what each function does
- Use __name__ == "__main__": Add test code inside this guard
- Keep imports at the top: All import statements go at the beginning of the file
- Avoid circular imports: If module A imports B and B imports A, you will get errors
Check Your Understanding
You have a file called utils.py with a function format_name(). How would you import and call that function in another file?
You have two main options:
Option 1: import utils then call utils.format_name("alice")
Option 2: from utils import format_name then call format_name("alice")
Both files must be in the same directory for the import to work.
Key Takeaways
- Any
.pyfile can be imported as a module - Use
if __name__ == "__main__":to separate reusable code from test/run code - Group related functions in the same module file
- Use descriptive file names and add docstrings to functions
- Keep your project organized: one main entry point, separate modules for different tasks
- Both the importing file and the module must be in the same directory (for simple imports)