Input argument in new method incorrectly reports that its type is not defined even though it was imported
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
Input argument in new method incorrectly reports that its type is undefined
I import the decimal module, I have an input in __new__ named decimal of type decimal.Decimal
Python code runs but mypy reports:
input_collision.py:116: error: Name "decimal.Decimal" is not defined [name-defined]
input_collision.py:120: error: Argument 2 for "super" not an instance of argument 1 [misc]
To Reproduce
from __future__ import annotations
import decimal
import typing
import typing_extensions
"""
MIT License
Copyright (c) 2020 Corentin Garcia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# above license is for the immutabledict class
_K = typing.TypeVar("_K")
_V = typing.TypeVar("_V", covariant=True)
class immutabledict(typing.Mapping[_K, _V]):
"""
An immutable wrapper around dictionaries that implements
the complete :py:class:`collections.Mapping` interface.
It can be used as a drop-in replacement for dictionaries
where immutability is desired.
Note: custom version of this class made to remove __init__
"""
dict_cls: typing.Type[typing.Dict[typing.Any, typing.Any]] = dict
_dict: typing.Dict[_K, _V]
_hash: typing.Optional[int]
@classmethod
def fromkeys(
cls, seq: typing.Iterable[_K], value: typing.Optional[_V] = None
) -> "immutabledict[_K, _V]":
return cls(dict.fromkeys(seq, value))
def __new__(cls, arg: typing.Dict):
inst = super().__new__(cls)
setattr(inst, '_dict', cls.dict_cls(arg))
setattr(inst, '_hash', None)
return inst
def __getitem__(self, key: _K) -> _V:
return self._dict[key]
def __contains__(self, key: object) -> bool:
return key in self._dict
def __iter__(self) -> typing.Iterator[_K]:
return iter(self._dict)
def __len__(self) -> int:
return len(self._dict)
def __repr__(self) -> str:
return "%s(%r)" % (self.__class__.__name__, self._dict)
def __hash__(self) -> int:
if self._hash is None:
h = 0
for key, value in self.items():
h ^= hash((key, value))
self._hash = h
return self._hash
def __or__(self, other: typing.Any) -> immutabledict[_K, _V]:
if not isinstance(other, (dict, self.__class__)):
return NotImplemented
new = dict(self)
new.update(other)
return self.__class__(new)
def __ror__(self, other: typing.Any) -> typing.Dict[typing.Any, typing.Any]:
if not isinstance(other, (dict, self.__class__)):
return NotImplemented
new = dict(other)
new.update(self)
return new
def __ior__(self, other: typing.Any) -> immutabledict[_K, _V]:
raise TypeError(f"'{self.__class__.__name__}' object is not mutable")
class MyDict(immutabledict[str, typing.Any]):
@property
def decimal(self) -> typing.Union[decimal.Decimal, None]:
val = self.get("decimal")
if val is None:
return val
return typing.cast(
decimal.Decimal,
val
)
def __new__(
cls: typing.Type[immutabledict],
decimal: typing.Union[decimal.Decimal, None] = None
):
arg = {}
arg['decimal'] = decimal
inst = super().__new__(cls, arg)
return typing.cast(MyDict, inst)
inst = MyDict(decimal=decimal.Decimal('3.14'))
print(inst)
Expected Behavior
I expect mypy to understand that decimal was imported earlier and I can use decimal.Decimal as my type hint.
Actual Behavior
Mypy gets confused and reports:
input_collision.py:116: error: Name "decimal.Decimal" is not defined [name-defined]
input_collision.py:120: error: Argument 2 for "super" not an instance of argument 1 [misc]
Your Environment
- Mypy version used: 1.4.1 (compiled: yes)
- Mypy command-line flags: mypy input_collision.py
- Mypy configuration options from
mypy.ini(and other config files): n/a - Python version used:Python 3.9.17 (main, Jun 6 2023, 14:44:03) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Esegui mypy input_collision.py con il reproducer fornito e verifica come le annotazioni in new gestiscono il nome decimal importato quando un parametro ha lo stesso nome. Il lavoro è completato quando l’annotazione decimal.Decimal viene accettata e l’errore super() segnalato viene risolto, mentre l’esempio continua a essere eseguito come previsto.
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
- 38/100