python / python/mypy

Wrong test result for default values of Mapping arguments

Offen
#16,716 9 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

It seems that the validation of

def foo(x: Mapping[str, str] = some_default) -> None:
    pass 

yields strange results depending on the declared type of some_default.

To Reproduce

use mypy --strict on the following file

"""
This file is part of python-none-objects library.

python-none-objects is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

python-none-objects is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with python-none-objects.
If not, see <http://www.gnu.org/licenses/>.

©Copyright 2023 Laurent Lyaudet
"""
"""
The empty tuple is really useful.
But it is implementation dependent for it to be a constant:
https://docs.python.org/3.12/reference/expressions.html#parenthesized-forms
https://stackoverflow.com/questions/41983180/is-the-empty-tuple-in-python-a-constant
https://stackoverflow.com/questions/8185776/compare-object-to-empty-tuple-with-the-is-operator-in-python-2-x
https://stackoverflow.com/questions/38328857/why-does-is-return-true-when-is-and-is-return-false
https://stackoverflow.com/questions/14135542/how-is-tuple-implemented-in-cpython
I'm wondering if there would be additional efficiency gains
to treat the empty tuple and the constants here differently
at execution of Python scripts.
"""
# from typing import Iterable, Container, Collection, Mapping
from types import MappingProxyType
from typing import Any, Mapping, Never

NoneIterable = ()
NoneContainer = NoneIterable
NoneCollection = NoneIterable
NoneMapping1: Mapping[Any, str] = {123: "abc"}  # MappingProxyType({})
NoneMapping2: Mapping[str, Any] = {"abc": 123}  # MappingProxyType({})
NoneMapping3: Mapping[Never, Any] = MappingProxyType({})
NoneMapping4: Mapping[Any, Never] = MappingProxyType({})
NoneMapping5: Mapping[Any, Any] = {"abc": 123}  # MappingProxyType({})
NoneMapping6: Mapping[Never, Never] = MappingProxyType({})


def foo1(x: Mapping[str, str] = NoneMapping1) -> None:
    # Pass typing but {123: "abc"} is a Mapping[Any, "str"]
    # and it should not be valid.
    for y, z in x.items():
        print(f"foo {y} bar {z}")


def foo2(x: Mapping[str, str] = NoneMapping2) -> None:
    # Pass typing but {"abc": 123} is a Mapping[str, Any]
    # and it should not be valid.
    for y, z in x.items():
        print(f"foo {y} bar {z}")

def foo3(x: Mapping[str, str] = NoneMapping3) -> None:
    # Fails typing but only an empty mapping is a Mapping[Never, Any]
    # and it is also a Mapping[str, str].
    for y, z in x.items():
        print(f"foo {y} bar {z}")


def foo4(x: Mapping[str, str] = NoneMapping4) -> None:
    # Pass typing
    for y, z in x.items():
        print(f"foo {y} bar {z}")


def foo5(x: Mapping[str, str] = NoneMapping5) -> None:
    # Pass typing but {"abc": 123} is a Mapping[Any, Any]
    # and it should not be valid.
    for y, z in x.items():
        print(f"foo {y} bar {z}")


def foo6(x: Mapping[str, str] = NoneMapping6) -> None:
    # Fails typing but only an empty mapping is a Mapping[Never, Never]
    # and it is also a Mapping[str, str].
    for y, z in x.items():
        print(f"foo {y} bar {z}")

# Or even better, a reproducible playground link https://mypy-play.net/ (use the "Gist" button)

Expected Behavior

I thought that cases 3, 4, 6 would pass since the only possible value for the default is an empty mapping.
And I thought that cases 1, 2, 5 would fail.

Actual Behavior

$mypy --strict ./test_mypy_on_pno.py
test_mypy_on_pno.py:60: error: Incompatible default for argument "x" (default has type "Mapping[NoReturn, Any]", argument has type "Mapping[str, str]") [assignment]
test_mypy_on_pno.py:80: error: Incompatible default for argument "x" (default has type "Mapping[NoReturn, NoReturn]", argument has type "Mapping[str, str]") [assignment]

Only cases 3 and 6 fails, when both should pass.

Your Environment

  • Mypy version used: mypy 1.8.0 (compiled: yes)
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.11

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Führe zunächst den bereitgestellten Reproducer mit mypy 1.8.0 und dem --strict-Flag aus und vergleiche dann die gemeldeten Ergebnisse für foo1 bis foo6 mit dem erwarteten Verhalten. Erledigt ist die Aufgabe, wenn die Fälle 3, 4 und 6 bestehen, während die Fälle 1, 2 und 5 als inkompatible Standardwerte abgelehnt werden.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.