[Python] Pylance type error supplying SQLAlchemy NVARCHAR length

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    Pylance is raising a type error when I include a length for the NVARCHAR column in the below script:

    import urllib.parse
    import uuid

    import pandas as pd
    from sqlalchemy import create_engine
    from sqlalchemy.types import NVARCHAR
    from sqlalchemy.dialects.mssql import UNIQUEIDENTIFIER

    # CREATE DATABASE CONNECTION
    connection = create_engine(
    f"mssql+pyodbc:///?odbc_connect={
    urllib.parse.quote_plus(
    'DRIVER=' + <driver details here> + ';'
    'SERVER=' + <server details here> + ';'
    'DATABASE=' + <db details here> + ';'
    'UID=' + <uid details here> + ';'
    'PWD=' + <pwd details here> + ';'
    'Authentication=' + <auth details here>
    )
    }"
    )

    # CREATE DATAFRAME
    df = pd.DataFrame(
    columns=['id', 'name'],
    data=[
    [str(uuid.uuid4()), 'hello'],
    [str(uuid.uuid4()), 'world'],
    [str(uuid.uuid4()), 'foo'],
    [str(uuid.uuid4()), 'bar'],
    [str(uuid.uuid4()), 'baz'],
    ]
    )

    # SAVE DATA
    df.to_sql(
    'test',
    con=connection,
    dtype={
    'id': UNIQUEIDENTIFIER,
    'name': NVARCHAR(length=1024),
    },
    index=False,
    )



    Specifically, it raises 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".

    If I remove the length parameter on NVARCHAR the error goes away, but I need to be able to specify the length.

    Am I doing something wrong or is this a bug in Pyright/Pylance?

    Continue reading...

Compartilhe esta Página