Mypy error is not reproducible in local environment

141 Views Asked by At

I have a github action and pre-commit hook for my python code

Below is my yml file for the git action

name: Mypy

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.11"]
    steps:
    - uses: actions/checkout@v3
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v3
      with:
        python-version: ${{ matrix.python-version }}
    - name: Install dependencies
      run: |
        pip install "mypy==1.7.0" "pydantic>=2.4" "alembic>=1.8.1" "types-aiofiles>=23.2.0" "types-redis>=4.6.0" --quiet
    - name: Running mypy checks
      run: |
        mypy . --ignore-missing-imports --config-file backend/app/mypy.ini

here is my pre-commit config

repos:

-   repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.7.0
    hooks:
    -   id: mypy
        args: [--ignore-missing-imports, --config-file, backend/app/mypy.ini]
        verbose: true
        additional_dependencies:
        - "pydantic>=2.4"
        - "alembic>=1.8.1"
        - "types-aiofiles>=23.2.0"
        - "types-redis>=4.6.0"

The code I am checking looks like this

    async def total_monthly_size(self, user_id: int) -> int:
        now = utcnow()
        current_month = datetime(now.year, now.month, 1)
        sum_total_size_query = select(func.sum(self.model.total_size or self.model.estimated_total_size)).where(
            self.model.user_id == user_id,
            self.model.is_failed.is_(False),
            self.model.requested_at > current_month,
        )

        sum_total_size_result = await self._db.execute(sum_total_size_query)
        sum_total_size = sum_total_size_result.scalar()
        return int(sum_total_size or 0)

pre-commit runs without errors but git action fails with

error: Need type annotation for "sum_total_size_query"  [var-annotated]

How do I achieve the consistent behavior of both tools?

UPDATE: When I run the git action's command in the local environment, I do not get an error as well:

mypy . --ignore-missing-imports --config-file backend/app/mypy.ini
1

There are 1 best solutions below

1
anthony sottile On

you are not comparing apples-to-apples

pre-commit works by passing filenames as positional arguments to hooks

so instead of comparing against mypy . ... you'd want to compare against mypy ... $(git ls-files -- '*.py')


disclaimer: I wrote pre-commit