danielgtaylor / danielgtaylor/python-betterproto
Shorter optional fields
- Lenguaje dominante
- Python
- Estrellas
- 1.8k
- Forks
- 234
- Métricas de merge de PR
- Sin PR fusionados en 30 d
Descripción
Optional fields generate very long and repetitive code.
The idea is to use shorter and simpler code, and internally consider it as a field having `optional=True, group=f"_{field_name}"`.
Related to #459.
### Proto file
```proto
syntax = "proto3";
message Foo {
optional uint32 bar = 1;
};
```
### Currently generated code
```py
from dataclasses import dataclass
import betterproto
@dataclass(eq=False, repr=False)
class Foo(betterproto.Message):
bar: Optional[int] = betterproto.uint32_field(
1, optional=True, group="_bar"
)
```
### Idea A
Read the type-hint of the field, and if it's a union of a type with `None`, consider it an optional field.
This might be a bad idea if unions of a type + `None` are used for something other than optional fields.
An example implementation of detecting optional fields can be found here: [`cattrs/converters.py`](https://github.com/python-attrs/cattrs/blob/e1db1f24fc884e152f8d19ee02de24d87e97e55a/src/cattrs/converters.py#L109-L110).
```py
from dataclasses import dataclass
from typing import Union, Optional
import betterproto
@dataclass(eq=False, repr=False)
class Foo(betterproto.Message):
bar: Optional[int] = betterproto.uint32_field(1)
```
### Idea B
Use a custom type-hint that indicates a field is optional, and is correctly understood by type-checkers as `Optional`.
```py
from dataclasses import dataclass
import betterproto
@dataclass(eq=False, repr=False)
class Foo(betterproto.Message):
bar: betterproto.OptionalField[int] = betterproto.uint32_field(1)
```
It could possibly be implemented something like this:
[`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated)
```py
from typing import Optional, TypeVar
from typing_extensions import Annotated
T = TypeVar("T")
optional_metadata = object() # or another sentinel
OptionalField = Annotated[Optional[T], optional_metadata]
```
### Idea C
Automatically add `group=f"_{field_name}"` if `optional=True` and no `group` specified.
```py
from dataclasses import dataclass
import betterproto
@dataclass(eq=False, repr=False)
class Foo(betterproto.Message):
bar: Optional[int] = betterproto.uint32_field(1, optional=True)
```
Guía de contribución
Línea de trabajo
Comienza siguiendo la ruta del generador que produce campos de Python para campos opcionales de proto3; el issue no indica archivos ni tests del repositorio. Revisa el ejemplo referenciado cattrs/converters.py y compara Ideas A, B y C antes de elegir un enfoque. Se considera terminado cuando los campos opcionales generan código más corto, preservando al mismo tiempo la tipificación correcta de Optional y el seguimiento de la presencia.
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
- 30/100