Skip to content

Commit 48ea4ea

Browse files
committed
feat: useOptionals=all
1 parent 59948e6 commit 48ea4ea

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

src/betterproto/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -1439,6 +1439,8 @@ def to_dict(
14391439
elif field_is_repeated:
14401440
# Convert each item.
14411441
cls = self._betterproto.cls_by_field[field_name]
1442+
if not value:
1443+
value = []
14421444
if cls == datetime:
14431445
value = [_Timestamp.timestamp_to_json(i) for i in value]
14441446
elif cls == timedelta:

src/betterproto/plugin/models.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,20 @@
2929
reference to `A` to `B`'s `fields` attribute.
3030
"""
3131

32-
3332
import builtins
3433
import re
3534
import textwrap
3635
from dataclasses import (
3736
dataclass,
3837
field,
3938
)
39+
40+
41+
try:
42+
from typing import Literal
43+
except ImportError:
44+
from typing_extensions import Literal
45+
4046
from typing import (
4147
Dict,
4248
Iterable,
@@ -250,6 +256,7 @@ class OutputTemplate:
250256
services: List["ServiceCompiler"] = field(default_factory=list)
251257
imports_type_checking_only: Set[str] = field(default_factory=set)
252258
pydantic_dataclasses: bool = False
259+
use_optionals: Optional[Literal["all"]] = None
253260
output: bool = True
254261

255262
@property
@@ -483,7 +490,7 @@ def repeated(self) -> bool:
483490

484491
@property
485492
def optional(self) -> bool:
486-
return self.proto_obj.proto3_optional
493+
return self.proto_obj.proto3_optional or self.output_file.use_optionals == "all"
487494

488495
@property
489496
def mutable(self) -> bool:

src/betterproto/plugin/parser.py

+3
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ def generate_code(request: CodeGeneratorRequest) -> CodeGeneratorResponse:
9898
output_package_name
9999
].pydantic_dataclasses = True
100100

101+
if "useOptionals=all" in plugin_options:
102+
request_data.output_packages[output_package_name].use_optionals = "all"
103+
101104
# Read Messages and Enums
102105
# We need to read Messages before Services in so that we can
103106
# get the references to input/output messages for each service

0 commit comments

Comments
 (0)