Type Stubs for PyMySQL

1.1.0.20260408 · active · verified Thu Apr 09

This package provides static type annotations (stubs) for the PyMySQL library, enabling type checkers like Mypy or Pyright to analyze code that uses PyMySQL. It helps catch type-related errors before runtime and improves IDE autocomplete and refactoring. The current version is 1.1.0.20260408, with updates often aligned with new `pymysql` releases or as needed by the typeshed project.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use PyMySQL with type hints. Installing `types-pymysql` allows your type checker to understand the types returned by `pymysql.connect`, `conn.cursor()`, and methods like `cursor.execute()` and `cursor.fetchall()`, improving code quality and maintainability. Remember that `types-pymysql` provides *stubs*; you still need to `pip install pymysql` to run this code at runtime.

import pymysql
from pymysql.cursors import DictCursor
import os

# These environment variables simulate configuration for a MySQL database.
# Replace with your actual database details or set environment variables.
DB_HOST = os.environ.get('MYSQL_HOST', 'localhost')
DB_USER = os.environ.get('MYSQL_USER', 'root')
DB_PASSWORD = os.environ.get('MYSQL_PASSWORD', 'password')
DB_NAME = os.environ.get('MYSQL_DB', 'test_db')

def get_example_data() -> list[dict]:
    """Connects to a MySQL database and fetches some example data."""
    try:
        # types-pymysql provides type hints for pymysql.connect's return (Connection)
        with pymysql.connect(
            host=DB_HOST,
            user=DB_USER,
            password=DB_PASSWORD,
            database=DB_NAME,
            cursorclass=DictCursor # Type stubs help with DictCursor return types
        ) as conn: # 'conn' is typed as 'pymysql.connections.Connection'
            with conn.cursor() as cursor: # 'cursor' is typed as 'pymysql.cursors.DictCursor'
                # Type stubs ensure 'execute' and 'fetchall' method signatures are known
                cursor.execute("SELECT 1 as id, 'hello' as message")
                result: list[dict] = cursor.fetchall()
                return result
    except pymysql.Error as e:
        print(f"Database connection or query error: {e}")
        return []

if __name__ == "__main__":
    # This code requires 'pymysql' to be installed and a running MySQL server.
    # 'types-pymysql' enhances static analysis of this code.
    data = get_example_data()
    if data:
        print("Fetched data:", data)
    else:
        print("Failed to fetch data. Check database connection and `pymysql` installation.")

view raw JSON →