Hacktoberfest 2026:メンテナが10月に向けて印を付けた、オープンで初心者向けの issue。 Hacktoberfest の issue を見る

Shorter optional fields

オープン
#499 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
30/100
issue の種類
機能追加
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
python
領域
tooling

調査の方向性

proto3 の optional フィールド用の Python フィールドを生成するジェネレーターの経路を追跡することから始めてください。この issue ではリポジトリのファイルやテストは指定されていません。参照されている cattrs/converters.py の例を確認し、アプローチを選ぶ前に Ideas A、B、C を比較してください。完了の条件は、optional フィールドが、正しい Optional の型付けと presence tracking を維持しながら、より短いコードを生成することです。

索引モデルが issue の本文から書いたものです。

説明

enhancement medium

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
syntax = "proto3";

message Foo {
    optional uint32 bar = 1;
};
Currently generated code
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.

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.

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

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.

from dataclasses import dataclass

import betterproto


@dataclass(eq=False, repr=False)
class Foo(betterproto.Message):
    bar: Optional[int] = betterproto.uint32_field(1, optional=True)
主要言語
Python
スター
1.8k
フォーク
235
PR マージ指標
30日以内にマージされた PR はありません

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

danielgtaylor/python-betterproto のほかの issue

danielgtaylor/python-betterproto の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。