python / python/typing

Consider loosening restrictions of `Final`

Abierto
#920 9 comentarios 1 reacción 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 think that Final is a very based idea, but I feel that it's current restrictions make using it painful.

I think that split assignments should be allowed:

def foo(cond: bool) -> None:
    if cond:
        a: Final = Funny("spam")
    else:
        a: Final = Funny("eggs")  # this is currently an error

Most languages allow this pattern to initialize constant variables:

def foo(cond: bool) -> None:
    a: Final[Funny]
    if cond:
        a = Funny("spam")
    else:
        a = Funny("eggs")

I think these are convenient and enables Final to be used in more scenarios, but this is currently an error.
But this is allowed:

def foo(cond: bool) -> None:
    a: Final = Funny("spam") if cond else Funny("eggs")

Another issue I've found is the prohibition of Final declarations within loops:

def foo() -> None:
    for i in [1,2,3]:
        a: Final = i * 2  # currently an error
        a = 10  # error
        print(a)
    print(a)
    a = 10  # error

This is defined in the pep:

Note that a type checker need not allow Final declarations inside loops since the runtime will see multiple assignments to the same variable in subsequent iterations.

I understand that at runtime the same variable is reused for each iteration of the loop, but if you ignore that fact and just look at the semantic meaning of the code, it matches exactly to this Kotlin example:

fun foo() {
    val a = listOf(1, 2, 3).map { i ->
        val a = i
        a = 10  // error
        println(a)
        a
    }.last()
    println(a)
    a = 10  // error
}

Disallowing Final in loops doesn't address any of the motivations listed in the pep, any I can't see any reason why it should be disallowed.

Also, why are Final annotations not allowed on functional arguments?

Final may only be used as the outermost type in assignments or variable annotations. Using it in any other position is an error. In particular, Final can't be used in annotations for function arguments:

Why? This is commonly seen in other languages. In Kotlin, function parameters can only be val(Kotlin's form of Final), in Java a function parameter may be marked with final.

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 ni pruebas. Empieza revisando las reglas actuales de Final y los pasajes de PEP citados en el issue; después, lee el hilo de comentarios para conocer las objeciones anteriores. Se considera terminado cuando se haya tomado una decisión clara sobre las asignaciones divididas, las declaraciones de bucles y las anotaciones de los argumentos de funciones, y se haya registrado el comportamiento aceptado en la especificación de typing correspondiente.

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
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.