Skip to content

BUG: dtype parameter of DataFrame.to_sql() rejects SQLAlchemy type instances #1762

@philipnye

Description

@philipnye

Describe the bug

The dtype parameter of DataFrame.to_sql() raises a type error when passing SQLAlchemy type instances (e.g. NVARCHAR(length=1024)). Pandas itself accepts instances — this was explicitly made possible in pandas#9138 — but the stubs do not reflect this.

The error from Pyright/Pylance is:

Argument of type "dict[str, type[UNIQUEIDENTIFIER[_UUID_RETURN@UNIQUEIDENTIFIER]] | NVARCHAR]" cannot be assigned to parameter "dtype" of type "DtypeArg | None" in function "to_sql".

To Reproduce

  1. Minimal example:
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.types import NVARCHAR
from sqlalchemy.dialects.mssql import UNIQUEIDENTIFIER
import uuid

engine = create_engine("mssql+pyodbc://...")

df = pd.DataFrame(
    columns=['id', 'name'],
    data=[[str(uuid.uuid4()), 'hello']]
)

df.to_sql(
    'test',
    con=engine,
    dtype={
        'id': UNIQUEIDENTIFIER,
        'name': NVARCHAR(length=1024),  # instance, not class
    },
    index=False,
)
  1. Type checker: Pyright/Pylance

  2. Error message:

Argument of type "dict[str, type[UNIQUEIDENTIFIER[_UUID_RETURN@UNIQUEIDENTIFIER]] | NVARCHAR]" cannot be assigned to parameter "dtype" of type "DtypeArg | None" in function "to_sql".

Please complete the following information:

  • OS: Windows 11
  • OS Version: 10.0.26100
  • Python version: 3.13.0
  • Type checker version: 2026.2.1
  • pandas-stubs version: 3.0.3.260530

Additional context

Originally reported at pandas-dev/pandas#61660, where maintainers confirmed this should be filed against pandas-stubs.

The dtype argument to to_sql() accepts a dict of column names to SQLAlchemy types, and SQLAlchemy types are commonly passed as instances in order to configure parameters like length. The DtypeArg type does not appear to accommodate SQLAlchemy type instances (only classes), which means valid pandas usage cannot be correctly typed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions