Type Stubs for PyMySQL
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
- gotcha Installing `types-pymysql` provides *only* type annotations (stubs); it does not install the `pymysql` library itself. You must `pip install pymysql` separately for your application to function at runtime.
- gotcha Type stubs are consumed by static type checkers (e.g., Mypy, Pyright). If your type checker isn't finding the stubs, ensure it's properly configured to discover installed type packages. Some environments might require explicit configuration for stub discovery.
- gotcha Type stubs in typeshed might occasionally lag behind the absolute latest features or minor versions of `pymysql`. While efforts are made to keep them up-to-date, new `pymysql` releases might introduce changes not immediately reflected in the stubs, leading to `Any` types or type-checking errors for very new features.
Install
-
pip install types-pymysql
Imports
- pymysql
import pymysql
- Connection
from pymysql import Connection
- DictCursor
from pymysql.cursors import DictCursor
Quickstart
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.")