Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 279
Vic Avatar asked Mar 05 '26 23:03

Vic


1 Answers

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.

like image 99
Brian Avatar answered Mar 07 '26 11:03

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!