python / python/mypy

Reusing variable name in different scopes

Abierto
#5,750 5 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

false-positive priority-1-normal topic-union-types topic-usability
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

I saw that there is a similar bug around redefining a variable, but I believe this one is slightly different problem, here is the code:

#! /usr/bin/env python

from typing import Dict, List, Union

def main(arg):
	# type: (bool) -> Union[Dict[str, str], List[str]]

	if arg:
		var = list()
		var.append('something')
	else:
		var = dict()
		var['key'] = 'something'

	return var


if __name__ == '__main__':
	main(True)

The variable var while it uses the same name, it is technically a different variable, but mypy 0.630 is complaining about it:

$ ../py37/bin/mypy --python-executable ../py27/bin/python test.py
test.py:12: error: Incompatible types in assignment (expression has type "Dict[<nothing>, <nothing>]", variable has type "List[str]")
test.py:13: error: No overload variant of "__setitem__" of "list" matches argument types "str", "str"
test.py:13: note: Possible overload variants:
test.py:13: note:     def __setitem__(self, int, str) -> None
test.py:13: note:     def __setitem__(self, slice, Iterable[str]) -> None

Ideally it should have no problem with it and at the point where there is return statement it should just do an union so the type would be Union[Dict[str, str], List[str]]

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Empieza con el caso reproducible de test.py y la función main mostrada en el issue; después, sigue cómo mypy infiere los tipos de var a través de las ramas if y else. Se considera terminado cuando el ejemplo no produce errores de incompatible-assignment ni de setitem y el retorno se trata como Union[Dict[str, str], List[str]].

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
compilers
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.