Type narrowing and PEP 634 pattern matching
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Feature
Narrowing a type in a case block that matches the True result of a type-narrowing expression.
Pitch
Hi all- I'd be curious to hear opinions on how realistic the above would be. Here's an example of something that would work if this were implemented:
a: str | None = "hello"
match a is not None: # or `match isinstance(a, str)`, etc.
case True:
print("'a' is a string", a.encode()) # currently: Item "None" of "str | None" has no attribute "encode"
case False:
print("'a' is None")
My "pitch" is simply that this feels like it should work (even though it makes sense to me why it doesn't). I think this feeling comes from the fact that, at least on the surface:
if thing:
blah()
else:
whatev()
seems morally equivalent to
match thing:
case True:
blah()
case False:
whatev()
Since I don't have any background with mypy's internals, I'm hoping to hear from the team here how feasible this all sounds.
For context, I ran into this issue when I had a type-narrowing expression embedded in a larger scrutinee (in practice, I can't imagine using match over if if the only thing I were testing was the result of a single type-narrowing expression). Specifically, I was creating a decision table of sorts, and match seemed like a nice way to do that without having to repeat tests:
content: str | bytes
is_text_format: bool
match isinstance(content, str), is_text_format:
case True, True:
prepped = content
case True, False:
prepped = content.encode("utf-8") # type narrowing useful here
case False, True:
prepped = content.decode("utf-8") # and here
case False, False:
prepped = content
...
I'm sure there are better ways to tackle this bool-centric example, but I think the general question stands on its own outside my original context.
Thank you for your consideration!
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza con los dos ejemplos de match del issue y compara su comportamiento de narrowing solicitado con los diagnósticos actuales de mypy. El issue no identifica ningún archivo fuente, prueba ni punto de entrada, por lo que localizar la implementación de pattern matching y type narrowing formaría parte del trabajo. Se considera terminado cuando las ramas de True y False restringen la expresión evaluada de forma coherente, incluidos los scrutinees de tuplas.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 25/100