Course Topics
Python Basics Introduction and Setup Syntax and Indentation Comments and Documentation Running Python Programs Exercise Variables and Data Types Variables and Assignment Numbers (int, float, complex) Strings and Operations Booleans and None Type Conversion Exercise Operators Arithmetic Operators Comparison Operators Logical Operators Assignment Operators Bitwise Operators Exercise Input and Output Getting User Input Formatting Output Print Function Features Exercise Control Flow - Conditionals If Statements If-Else Statements Elif Statements Nested Conditionals Exercise Control Flow - Loops For Loops While Loops Loop Control (break, continue) Nested Loops Exercise Data Structures - Lists Creating and Accessing Lists List Methods and Operations List Slicing List Comprehensions Exercise Data Structures - Tuples Creating and Accessing Tuples Tuple Methods and Operations Tuple Packing and Unpacking Exercise Data Structures - Dictionaries Creating and Accessing Dictionaries Dictionary Methods and Operations Dictionary Comprehensions Exercise Data Structures - Sets Creating and Accessing Sets Set Methods and Operations Set Comprehensions Exercise Functions Defining Functions Function Parameters and Arguments Return Statements Scope and Variables Lambda Functions Exercise String Manipulation String Indexing and Slicing String Methods String Formatting Regular Expressions Basics Exercise File Handling Opening and Closing Files Reading from Files Writing to Files File Modes and Context Managers Exercise Error Handling Understanding Exceptions Try-Except Blocks Finally and Else Clauses Raising Custom Exceptions Exercise Object-Oriented Programming - Classes Introduction to OOP Creating Classes and Objects Instance Variables and Methods Constructor Method Exercise Object-Oriented Programming - Advanced Inheritance Method Overriding Class Variables and Methods Static Methods Exercise Modules and Packages Importing Modules Creating Custom Modules Python Standard Library Installing External Packages Exercise Working with APIs and JSON Making HTTP Requests JSON Data Handling Working with REST APIs Exercise Database Basics Introduction to Databases SQLite with Python CRUD Operations Exercise Final Project Project Planning Building Complete Application Code Organization Testing and Debugging Exercise

Creating Custom Modules

Introduction

Why this topic matters: Organizing your Python code into modules is a fundamental practice for maintaining a clean and scalable codebase. It promotes reusability, improves readability, and simplifies testing and debugging processes.

What you'll learn: In this tutorial, we will discuss how to create custom Python modules, import them into other scripts, and explore best practices for module design.

Core Concepts

A Python module is a file containing Python definitions and statements. The names defined in the module can be used from other Python programs after the module has been loaded. To create a new module, simply save your code in a .py file.

Important Terms:

  • Module: A Python file that contains definitions and functions.
  • Import Statement: A statement used to load a module into the current script.
  • Relative Paths: A way of referring to other modules located within the same directory or subdirectories.

Practical Examples

Let's create a simple module called math_utils.py that contains some useful mathematical functions:

# math_utils.py
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

Now, in another script main.py, we can import the math_utils module and use its functions:

# main.py
import math_utils

result = math_utils.add(3, 4)
print(result)  # Output: 7

result = math_utils.multiply(3, 5)
print(result)  # Output: 15

Common Issues and Solutions

NameError

What causes it: When you try to use a function or variable that is defined in another module but have not imported the module first.

# Wrong_approach.py
result = math_utils.add(3, 4)  # Import statement missing!

Error message:

Traceback (most recent call last):
  File "Wrong_approach.py", line 2, in <module>
    result = math_utils.add(3, 4)
NameError: name 'math_utils' is not defined

Solution: Always include the import statement at the beginning of your scripts.

Why it happens: Not including the import statement makes the interpreter unable to find the required module.

How to prevent it: Import the necessary modules before using their functions or variables.

AttributeError

What causes it: Trying to access a non-existent attribute, function, or variable within a module.

# Wrong_function.py
import math_utils

result = math_utils.wrong_function(3, 4)

Error message:

Traceback (most recent call last):
  File "Wrong_function.py", line 2, in <module>
    result = math_utils.wrong_function(3, 4)
AttributeError: module 'math_utils' has no attribute 'wrong_function'

Solution: Ensure that the function or variable you are trying to access is defined within the imported module.

Why it happens: The function or variable does not exist in the specified module, or there might be a typo in its name.

How to prevent it: Double-check your code for typos and make sure that the functions or variables you want to use are defined in the appropriate modules.

Best Practices

  • Use descriptive names for modules and their components (functions, classes, etc.). This helps others understand your code more easily.
  • Keep related functions and variables within the same module. Grouping related items promotes modularity and makes your code easier to maintain.
  • Avoid global variables. They can make your code harder to test and debug. Use local variables instead, or define functions that return values as needed.
  • Document your code using docstrings (triple quotes at the beginning of a function or class definition). This helps others understand what each part of your code does.

Key Takeaways

  • Creating custom modules in Python helps you organize and reuse your code.
  • Import statements allow you to use functions, classes, and variables from other modules.
  • Common issues like NameError and AttributeError can be resolved by carefully managing your imports and function names.
  • Follow best practices for naming conventions, organization, and documentation to write professional, maintainable code.
  • Next steps: Learn about advanced module concepts such as packages, __init__.py files, and the built-in importlib library.