Start Coding

Topics

Creating Python Modules

Python modules are essential for organizing and reusing code. They allow developers to break down complex programs into manageable, reusable components.

What is a Python Module?

A module is a file containing Python definitions and statements. It can define functions, classes, and variables that can be used in other Python programs.

Creating a Module

To create a module, simply write Python code in a file with a .py extension. For example:


# mymodule.py
def greet(name):
    return f"Hello, {name}!"

PI = 3.14159

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return PI * self.radius ** 2
    

Using a Module

To use a module in another Python script, use the import statement. There are several ways to import modules:

1. Importing the entire module


import mymodule

print(mymodule.greet("Alice"))
circle = mymodule.Circle(5)
print(circle.area())
    

2. Importing specific items


from mymodule import greet, PI

print(greet("Bob"))
print(PI)
    

Best Practices

  • Use meaningful names for your modules.
  • Keep modules focused on a specific functionality.
  • Include docstrings to document your module and its contents.
  • Use relative imports for modules within the same package.
  • Avoid circular imports between modules.

Module Search Path

Python searches for modules in the following locations:

  1. The current directory
  2. Directories listed in the PYTHONPATH environment variable
  3. Standard library directories
  4. Site-packages directories for third-party packages

You can view the module search path using the sys.path list from the Python sys Module.

Module vs. Script

When a Python file is run directly, its __name__ variable is set to '__main__'. This allows you to include code that runs only when the file is executed as a script, not when it's imported as a module:


# mymodule.py
def some_function():
    pass

if __name__ == '__main__':
    print("This runs only when executed directly")
    some_function()
    

Related Concepts

To further enhance your understanding of Python modules, explore these related topics:

By mastering module creation and usage, you'll be able to write more organized, maintainable, and reusable Python code.