python / python/mypy

mypy seems to use type from field definition instead of type of field_validator

Open
#15,977 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Description
I created a class that accepts a field with both a list[float] and a NDArray which converts it to NDArray after field validation (set to always via ConfigDict(validate_assignment = True)). However mypy complains about divide and substract operations over the vector field which should not as the field cannot be of type list[float] after validation.

At the moment I am using the # type: ignore[call-overload, operator] (Without those I get mypy errors).

image

Note: I have raised same issue in pydantic (https://github.com/pydantic/pydantic/issues/7262)

Example Code

import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field, computed_field, field_validator

class Vector(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True, validate_assignment=True)

    vector: NDArray[np.float64] | list[float] = Field(default=np.array([0.0, 0.0, 0.0]), min_length=3, max_length=3)

    @field_validator("vector")
    @classmethod
    def vector_validator(cls, v: NDArray[np.float64] | list[float]) -> NDArray:
        if isinstance(v, list):
            return np.array(v)
        return v

    @computed_field  # type: ignore[misc]
    @property
    def x(self) -> NDArray:
        return self.vector[0]

    @x.setter
    def x(self, value: float) -> None:
        self.vector[0] = value

    @computed_field  # type: ignore[misc]
    @property
    def y(self) -> NDArray:
        return self.vector[1]

    @y.setter
    def y(self, value: float) -> None:
        self.vector[1] = value

    @computed_field  # type: ignore[misc]
    @property
    def z(self) -> NDArray:
        return self.vector[2]

    @z.setter
    def z(self, value: float) -> None:
        self.vector[2] = value

    def to_unit(self) -> "Vector":
        return Vector(vector=self.vector / np.linalg.norm(self.vector))  # type: ignore[call-overload, operator]

    def __add__(self, other: "Vector") -> "Vector":
        return Vector(vector=self.vector + other.vector)

    def __sub__(self, other: "Vector") -> "Vector":
        return Vector(vector=self.vector - other.vector)  # type: ignore[operator]

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the Example Code through mypy and compare the reported errors with the validator's return type. Investigate how mypy represents the declared vector field type and whether field_validator information is available to type checking. Done means the shown divide and subtraction operations no longer require the listed type: ignore comments, with the existing behavior preserved.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
devtools, tooling
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.