Ability to use Callable type alias when annotating functions
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 1.8k
- Forks
- 302
- Merge medio
- 23 h
- PR fusionados (30 d)
- 8
Descripción
Hello. I would like to revive the discussion about Callable type aliases. The original discussion is here, and the related discussion about @declared_type is here and here.
The original thread contains a great example of the problem and a proposed solution:
from typing import Callable
import math
ActivationFunction = Callable[[float], float]
sigmoid: ActivationFunction
def sigmoid(x):
return 1 / (1 + math.exp(-x))
relu: ActivationFunction
def relu(x):
return max(0, x)
Another prosed solution is to use the @declared_type decorator:
@declared_type(ActivationFunction)
def sigmoid(x):
return 1 / (1 + math.exp(-x))
@declared_type(ActivationFunction)
def relu(x):
return max(0, x)
Currently, this can be done with Protocols, but it's too verbose:
from typing import Protocol
import math
class ActivationFunction(Protocol):
def __call__(self, x: float) -> float:
...
class Sigmoid(ActivationFunction):
def __call__(self, x: float) -> float:
return 1 / (1 + math.exp(-x))
class Relu(ActivationFunction):
def __call__(self, x: float) -> float:
return max(0, x)
sigmoid = Sigmoid()
relu = Relu()
print(sigmoid(0.5))
print(relu(0.5))
If the function is a single expression, it can be done very nicely with lambdas:
from typing import Callable
import math
ActivationFunction = Callable[[float], float]
sigmoid: ActivationFunction = lambda x: 1 / (1 + math.exp(-x))
relu: ActivationFunction = lambda x: max(0, x)
print(sigmoid(0.5))
print(relu(0.5))
Here's the equivalent FSharp code, with the only difference being that FSharp supports multiline lambdas:
type ActivationFunction = float -> float
let sigmoid: ActivationFunction = fun x -> 1.0 / (1.0 + exp(-x))
let relu: ActivationFunction = fun x -> max 0.0 x
printfn "%f" (sigmoid 0.5)
printfn "%f" (relu 0.5)
I'm asking about this feature because I'm reading a book called Domain Modeling Made Functional by Scott Wlaschin. In this book, the author recommends modeling the domain with types, including function type aliases, and focusing on the implementation details later. Here's an example from Chapter 9:
I'd like to try a similar approach in Python. Has there been any further discussion about this topic, or is there a workaround I'm unaware of? Thank you!
Guía de contribución
No hay ninguna guía de contribución indexada para este repositorio
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
Empieza leyendo las discusiones vinculadas en los issues 1641 y 2087 y en el pull request 3291; después, compara los enfoques propuestos de alias Callable y @declared_type con la solución alternativa basada en Protocol que se muestra aquí. Se considerará terminado cuando exista un comportamiento claramente elegido y aceptado para anotar definiciones de funciones, junto con el trabajo correspondiente de implementación y validación; este issue no especifica archivos ni pruebas.
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
- Necesita aclaración
- Aptitud para principiantes
- 25/100