Skip to content

Mypy errors: Incompatible type for optional ids & Incompatible type for SQLModel attribute in expression #267

Open
@javivdm

Description

@javivdm

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import Optional

from sqlmodel import SQLModel, create_engine, Session, Field, select


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str


engine = create_engine("sqlite:///.deleted/database.db")

SQLModel.metadata.create_all(engine)

hero_1 = Hero(name="Grey Hound")


def format_id(id: int):
    return f"{id:04d}"


with Session(engine) as session:
    session.add(hero_1)
    session.commit()
    session.refresh(hero_1)

    session.exec(select(Hero).where(Hero.id.in_([1, 2])))
    print(format_id(hero_1.id))

Description

When executing mypy on the code above I get the following output:

sqlmodel_mypy_issue.py:27: error: Item "int" of "Optional[int]" has no attribute "in_"
sqlmodel_mypy_issue.py:27: error: Item "None" of "Optional[int]" has no attribute "in_"
sqlmodel_mypy_issue.py:28: error: Argument 1 to "format_id" has incompatible type "Optional[int]"; expected "int"
Found 3 errors in 1 file (checked 1 source file)

So:

  • Is there any way to tell mypy that upon read a SQLmodel id has type int instead of Optional[int] without having to convert it to another model?
  • How should I build expressions such as .where(Hero.id.in_([1, 2])) so that mypy and Pycharm don't flag the in_ as not being an attribute of the model attribute type?

Thank you!

Operating System

Linux

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

Python 3.9.10

Additional Context

mypy version:
mypy 0.931

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions