python / python/typing

Types for "truthy" and "falsy" values

Abierto
#1,606 7 comentarios 4 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

topic: feature
Lenguaje dominante
Python
Estrellas
1.8k
Forks
302
Merge medio
23 h
PR fusionados (30 d)
8

Descripción

I found this function in our codebase and I'm trying to type it:

def run_until_truthy(fn, num_tries=5):
    for _ in range(num_tries):
        if res := fn():
            return res

    Exception('Giving up.')

The function repeatedly calls a callable without arguments until it returns a "truthy" value. Then it returns that value. Easy enough:

def run_until_truthy[T](fn: Callable[[], T], num_tries: int = 5) -> T: ...

This is correct but too restrictive. Usages like this don't work:

def load_something() -> str | None:
    pass

# mypy: Incompatible types in assignment (expression has type "str | None", variable has type "str")
something: str = run_until_truthy(load_something)

I can hack it to make it work:

type Falsy = Literal[None, False, 0, "", b""] | tuple[()]

def run_until_truthy[T](fn: Callable[[], T | Falsy], num_tries: int = 5) -> T: ...

Does it make sense to add official Truthy and Falsy types to the standard library?

Maybe a Truthy type would also make sense. Truthy can't be defined as a type alias of existing types, but could probably also be useful sometimes, e.g. to type the following function:

def get_falsy_values[T](seq: list[T | Truthy]) -> list[T]:
    return [i for i in seq if not i]

From thinking about it for a few minutes, I think Falsy would be more often useful than Truthy, at least in combination with the current typing features.


If there's an intersection type constructor at some point, the above examples could be written like this instead, which might be easier to understand:

def run_until_truthy[T](fn: Callable[[], T], num_tries: int = 5) -> T & Truthy: ...
def get_falsy_values[T](seq: list[T]) -> list[T & Falsy]:

2024-11-25

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

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

No se nombran archivos de implementación ni pruebas. Empieza revisando los ejemplos de truthy y falsy, luego lee las propuestas enlazadas sobre intersection types y las directrices del typing project; el trabajo solo está completo cuando se hayan acordado el diseño y el comportamiento esperado de la comprobación de tipos, y se haya especificado la compatibilidad relevante con typing.

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

Evaluación

Stack tecnológico
python
Área
tooling
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.