What are Python Source Files?

Python source files are files containing Python code with the .py extension. These files contain Python statements and definitions that can be executed directly or imported into other Python programs.

Key Point: Every Python source file is also a module. When you import a file, Python creates a module object from it.

Basic Python Source File Structure

A typical Python source file follows this structure:

Example: hello.py
# hello.py - A simple Python source file
# Module docstring (optional but recommended)
"""This module provides greeting functionality."""

# Import statements
import sys
import os

# Module-level variables (constants)
GREETING = "Hello, World!"
VERSION = "1.0.0"

# Function definitions
def say_hello(name="World"):
    """Return a greeting message."""
    return f"Hello, {name}!"

def calculate_sum(a, b):
    """Calculate the sum of two numbers."""
    return a + b

# Class definitions
class Greeter:
    """A class that handles greetings."""
    
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        return f"Hello from Greeter, {self.name}!"

# Main execution block (only runs if file is executed directly)
if __name__ == "__main__":
    print(say_hello("Python Developer"))
    greeter = Greeter("Alice")
    print(greeter.greet())
    result = calculate_sum(10, 20)
    print(f"10 + 20 = {result}")

The __name__ Variable

The __name__ variable is special in Python. It holds the name of the current module:

  • If the file is being run directly: __name__ == "__main__"
  • If the file is being imported: __name__ == "module_name"
Important: Always use if __name__ == "__main__": to prevent code from running when the module is imported.

Creating Python Modules

Modules are simply Python source files. To create a module:

Example: calculator.py
# calculator.py - A simple calculator module
"""A module providing basic arithmetic operations."""

def add(a, b):
    """Return the sum of a and b."""
    return a + b

def subtract(a, b):
    """Return the difference of a and b."""
    return a - b

def multiply(a, b):
    """Return the product of a and b."""
    return a * b

def divide(a, b):
    """Return the quotient of a divided by b."""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

# Using the module from another file:
# import calculator
# result = calculator.add(5, 3)

Importing Modules

There are several ways to import modules:

# Different ways to import modules

# 1. Import entire module
import calculator
result = calculator.add(10, 5)

# 2. Import with alias
import calculator as calc
result = calc.multiply(4, 6)

# 3. Import specific functions
from calculator import add, subtract
result = add(7, 3)

# 4. Import all functions (not recommended)
from calculator import *
result = divide(20, 4)
Best Practice: Avoid using from module import * as it can lead to namespace pollution and make debugging difficult.

Python Packages

Packages are directories containing multiple Python modules. They help organize related modules into a hierarchy.

Directory Structure
# Directory structure for a package:
# mypackage/
# ├── __init__.py
# ├── module1.py
# ├── module2.py
# └── subpackage/
#     ├── __init__.py
#     └── module3.py

# __init__.py can be empty or contain package initialization code
"""My Python package for demonstration."""

__version__ = "1.0.0"
__author__ = "Python Developer"

# You can expose specific functions at package level
from .module1 import main_function
from .module2 import helper_function

# Using the package:
# import mypackage
# from mypackage import module1
# from mypackage.subpackage import module3

Best Practices for Source Files

  1. Use descriptive names: File names should indicate their purpose
  2. Add docstrings: Document modules, functions, and classes
  3. Follow PEP 8: Use consistent formatting and style
  4. Keep files focused: Each file should have a single responsibility
  5. Use absolute imports: Better for clarity and maintainability

Executing Python Files

Python source files can be executed in several ways:

# 1. Direct execution from command line
# $ python script.py
# $ python3 script.py

# 2. Making a script executable (Unix/Linux/Mac)
# Add shebang line at the top of file:
#!/usr/bin/env python3
# Then make executable: chmod +x script.py
# Run directly: ./script.py

# 3. Using python -m to run as module
# $ python -m mypackage.module1

# 4. Interactive execution
# $ python -i script.py  # Runs script then enters interactive mode
Tip: Use python -m to run modules as scripts. This ensures Python adds the directory to sys.path properly.