microsoft / pyright

Static Type Checker for Python
Other
13.03k stars 1.39k forks source link

False positive inconsistent constructor if overloads are involved. #8372

Closed maflAT closed 1 month ago

maflAT commented 1 month ago

As soon as overloads are defined for __new__ or __init__ reportInconsistentConstructor will be triggered, even if the overloads are identical.

Code sample in pyright playground

from typing import Self, overload

class C:
    @overload
    def __new__(cls) -> Self: ...  # pyright:ignore[reportInconsistentOverload]
    def __new__(cls) -> Self:
        return cls()

    @overload
    def __init__(self) -> None: ...  # pyright:ignore[reportInconsistentOverload]
    def __init__(self) -> None:  
        pass
    # Mismatch between signature of __new__ and __init__ in class "C"
    # Signature of __init__ is "(self: C)"
    # Signature of __new__ is "(cls: type[Self@C])" Pylance(reportInconsistentConstructor)
erictraut commented 1 month ago

Thanks for the bug report. Yes, this is behaving incorrectly.

When pyright sees an overloaded __init__ or __new__, it is supposed to fall back on the overload's implementation to verify constructor consistency. The code was indeed doing this, but it was not binding the implementation to the class, which means that the self and cls parameters for __init__ and __new__ (respectively) will not match.

This will be fixed in the next release.

erictraut commented 1 month ago

This is addressed in pyright 1.1.372.