Skip to content

Commit 7efabc8

Browse files
committed
Make optional input fields NotRequired
1 parent e916165 commit 7efabc8

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

replit_river/codegen/client.py

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
Literal,
8181
Optional,
8282
Mapping,
83+
NotRequired,
8384
Union,
8485
Tuple,
8586
TypedDict,
@@ -507,7 +508,9 @@ def extract_props(tpe: RiverType) -> list[dict[str, RiverType]]:
507508
encoder_names.add(encoder_name)
508509
typeddict_encoder.append(f"{encoder_name}(x[{repr(name)}])")
509510
if name not in type.required:
510-
typeddict_encoder.append(f"if x[{repr(name)}] else None")
511+
typeddict_encoder.append(
512+
f"if {repr(name)} in x and x[{repr(name)}] else None"
513+
)
511514
elif isinstance(prop, RiverIntersectionType):
512515
encoder_name = TypeName(
513516
f"encode_{ensure_literal_type(type_name)}"
@@ -541,7 +544,12 @@ def extract_props(tpe: RiverType) -> list[dict[str, RiverType]]:
541544
items = cast(RiverConcreteType, prop).items
542545
assert items, "Somehow items was none"
543546
if is_literal(cast(RiverType, items)):
544-
typeddict_encoder.append(f"x[{repr(name)}]")
547+
if name in prop.required:
548+
typeddict_encoder.append(f"x[{repr(name)}]")
549+
else:
550+
typeddict_encoder.append(
551+
f"x.get({repr(safe_name)})"
552+
)
545553
else:
546554
match type_name:
547555
case ListTypeExpr(inner_type_name):
@@ -606,12 +614,24 @@ def extract_props(tpe: RiverType) -> list[dict[str, RiverType]]:
606614
)
607615
else:
608616
if name not in type.required:
609-
value = ""
610-
if base_model != "TypedDict":
611-
value = " = None"
612-
current_chunks.append(
613-
f" {name}: Optional[{render_type_expr(type_name)}]{value}"
614-
)
617+
if base_model == "TypedDict":
618+
current_chunks.append(
619+
reindent(
620+
" ",
621+
f"""\
622+
{name}: NotRequired[Optional[{render_type_expr(type_name)}]]
623+
""",
624+
)
625+
)
626+
else:
627+
current_chunks.append(
628+
reindent(
629+
" ",
630+
f"""\
631+
{name}: Optional[{render_type_expr(type_name)}] = None
632+
""",
633+
)
634+
)
615635
else:
616636
current_chunks.append(
617637
f" {name}: {render_type_expr(type_name)}"

0 commit comments

Comments
 (0)