python / python/mypy

Wrong test result for default values of Mapping arguments

Aperta
#16,716 9 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo il riproduttore fornito con mypy 1.8.0 e l’opzione --strict, quindi confronta i risultati riportati per foo1 fino a foo6 con il comportamento previsto. Il lavoro è completato quando i casi 3, 4 e 6 passano, mentre i casi 1, 2 e 5 vengono rifiutati perché hanno valori predefiniti incompatibili.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.