Crafting Modular Python Scripts with Functions and Classes

Discover techniques for breaking down your Python programs into modular components using functions and classes for improved code reusability and clarity.

0 likes
11 views

Rule Content

{
  "title": "Crafting Modular Python Scripts with Functions and Classes",
  "description": "Discover techniques for breaking down your Python programs into modular components using functions and classes for improved code reusability and clarity.",
  "category": "Python Cursor Rules",
  "rules": [
    {
      "name": "Use Functions for Reusable Code Blocks",
      "description": "Encapsulate repetitive or logically distinct code segments into functions to promote reusability and maintainability.",
      "examples": [
        {
          "before": "for i in range(10):\n    print(f'Processing item {i}')\n    # complex processing logic here",
          "after": "def process_item(i):\n    print(f'Processing item {i}')\n    # complex processing logic here\n\nfor i in range(10):\n    process_item(i)"
        }
      ]
    },
    {
      "name": "Define Classes for Related Data and Behavior",
      "description": "Group related data and methods into classes to create cohesive and modular code structures.",
      "examples": [
        {
          "before": "name = 'Widget'\nprice = 19.99\n\nprint(f'Product: {name}, Price: ${price}')",
          "after": "class Product:\n    def __init__(self, name, price):\n        self.name = name\n        self.price = price\n\n    def display(self):\n        print(f'Product: {self.name}, Price: ${self.price}')\n\nwidget = Product('Widget', 19.99)\nwidget.display()"
        }
      ]
    },
    {
      "name": "Follow PEP 8 Naming Conventions",
      "description": "Adhere to PEP 8 guidelines for naming functions and classes to ensure code consistency and readability.",
      "examples": [
        {
          "before": "def CalculateSum(a, b):\n    return a + b\n\nclass product:\n    def __init__(self, name, price):\n        self.name = name\n        self.price = price",
          "after": "def calculate_sum(a, b):\n    return a + b\n\nclass Product:\n    def __init__(self, name, price):\n        self.name = name\n        self.price = price"
        }
      ]
    },
    {
      "name": "Limit Function and Method Length",
      "description": "Keep functions and methods concise, ideally under 50 lines, to enhance readability and maintainability.",
      "examples": [
        {
          "before": "def process_data(data):\n    # 100 lines of processing logic",
          "after": "def process_data(data):\n    processed_data = step_one(data)\n    processed_data = step_two(processed_data)\n    return processed_data\n\ndef step_one(data):\n    # 25 lines of processing logic\n\ndef step_two(data):\n    # 25 lines of processing logic"
        }
      ]
    },
    {
      "name": "Use Docstrings for Functions and Classes",
      "description": "Provide clear docstrings for all functions and classes to document their purpose, parameters, and return values.",
      "examples": [
        {
          "before": "def add(a, b):\n    return a + b",
          "after": "def add(a, b):\n    \"\"\"\n    Add two numbers together.\n\n    Parameters:\n    a (int): The first number.\n    b (int): The second number.\n\n    Returns:\n    int: The sum of a and b.\n    \"\"\"\n    return a + b"
        }
      ]
    },
    {
      "name": "Avoid Global Variables",
      "description": "Minimize the use of global variables to reduce dependencies and potential side effects, enhancing modularity.",
      "examples": [
        {
          "before": "config = {'setting': True}\n\ndef process():\n    if config['setting']:\n        # processing logic",
          "after": "def process(config):\n    if config['setting']:\n        # processing logic\n\nconfig = {'setting': True}\nprocess(config)"
        }
      ]
    },
    {
      "name": "Implement Error Handling in Functions and Methods",
      "description": "Incorporate appropriate error handling within functions and methods to manage exceptions gracefully and maintain code robustness.",
      "examples": [
        {
          "before": "def divide(a, b):\n    return a / b",
          "after": "def divide(a, b):\n    try:\n        return a / b\n    except ZeroDivisionError:\n        return 'Error: Division by zero is undefined.'"
        }
      ]
    }
  ]
}