Search code examples
pythonpython-3.xsqlalchemypycharm

SQLAlchemy 2.0 ORM filter show wrong type in Pycharm


I'm using Pycharm to develop an app with SQLAlchemy 2.0.

When I attempt to query some table using ORM approach. Pycharm always display type error in the filter query.

For example, in the code snippet below:

    with Session(engine) as session:
        session.scalars(select(Albums.AlbumId).where(Albums.Id > user_last_sync_id))
                                                              ^^^ Show wrong type

Get the following message

Expected type 'ColumnElement[bool] | _HasClauseElement | SQLCoreOperations[bool] | ExpressionElementRole[bool] | () -> ColumnElement[bool] | LambdaElement',, got 'bool' instead

enter image description here

Even though it indicates a type error, but scripts still be executed (And get correct data) without showing any error messages.

What could potentially be causing this issue in the code? Is there a way to make code more "correct" to let Pycharm not to display type error?


Solution

  • PyCharm assumes that expressions of the form a > b evaluate to bool when no other type information is available. Most likely, SQLAlchemy isn't providing rich enough type hints and/or stubfiles for PyCharm to correctly infer the type of that expression.

    To resolve that warning, you can inform PyCharm about the true type of the expression using typing.cast:

    .where(
        cast("ColumnElement[bool]", Albums.Id > user_last_sync_id)
    )
    

    Alternatively, you can suppress the warning by adding # type: ignore to the end of the line.