Skip to content

Commit abec3c8

Browse files
committed
Default to None for optional func args
1 parent 648631b commit abec3c8

1 file changed

Lines changed: 42 additions & 4 deletions

File tree

internal/gen.go

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,15 @@ type pyType struct {
3838
IsNull bool
3939
}
4040

41-
func (t pyType) Annotation() *pyast.Node {
41+
func (t pyType) Annotation(isFuncSignature bool) *pyast.Node {
4242
ann := poet.Name(t.InnerType)
4343
if t.IsArray {
4444
ann = subscriptNode("List", ann)
4545
}
46-
if t.IsNull {
46+
if t.IsNull && isFuncSignature {
47+
ann = optionalKeywordNode("Optional", ann)
48+
}
49+
if t.IsNull && !isFuncSignature {
4750
ann = subscriptNode("Optional", ann)
4851
}
4952
return ann
@@ -69,9 +72,10 @@ type QueryValue struct {
6972
Typ pyType
7073
}
7174

75+
// Annotation in function signature
7276
func (v QueryValue) Annotation() *pyast.Node {
7377
if v.Typ != (pyType{}) {
74-
return v.Typ.Annotation()
78+
return v.Typ.Annotation(true)
7579
}
7680
if v.Struct != nil {
7781
if v.Emit {
@@ -143,12 +147,21 @@ func (q Query) AddArgs(args *pyast.Arguments) {
143147
})
144148
return
145149
}
150+
var optionalArgs []*pyast.Arg
146151
for _, a := range q.Args {
152+
if a.Typ.IsNull {
153+
optionalArgs = append(optionalArgs, &pyast.Arg{
154+
Arg: a.Name,
155+
Annotation: a.Annotation(),
156+
})
157+
continue
158+
}
147159
args.KwOnlyArgs = append(args.KwOnlyArgs, &pyast.Arg{
148160
Arg: a.Name,
149161
Annotation: a.Annotation(),
150162
})
151163
}
164+
args.KwOnlyArgs = append(args.KwOnlyArgs, optionalArgs...)
152165
}
153166

154167
func (q Query) ArgNodes() []*pyast.Node {
@@ -577,6 +590,31 @@ func subscriptNode(value string, slice *pyast.Node) *pyast.Node {
577590
}
578591
}
579592

593+
func optionalKeywordNode(value string, slice *pyast.Node) *pyast.Node {
594+
v := &pyast.Node{
595+
Node: &pyast.Node_Subscript{
596+
Subscript: &pyast.Subscript{
597+
Value: &pyast.Name{Id: value},
598+
Slice: slice,
599+
},
600+
},
601+
}
602+
return &pyast.Node{
603+
Node: &pyast.Node_Keyword{
604+
Keyword: &pyast.Keyword{
605+
Arg: string(pyprint.Print(v, pyprint.Options{}).Python),
606+
Value: &pyast.Node{
607+
Node: &pyast.Node_Constant{
608+
Constant: &pyast.Constant{
609+
Value: &pyast.Constant_None{None: true},
610+
},
611+
},
612+
},
613+
},
614+
},
615+
}
616+
}
617+
580618
func dataclassNode(name string) *pyast.ClassDef {
581619
return &pyast.ClassDef{
582620
Name: name,
@@ -617,7 +655,7 @@ func fieldNode(f Field) *pyast.Node {
617655
Node: &pyast.Node_AnnAssign{
618656
AnnAssign: &pyast.AnnAssign{
619657
Target: &pyast.Name{Id: f.Name},
620-
Annotation: f.Type.Annotation(),
658+
Annotation: f.Type.Annotation(false),
621659
Comment: f.Comment,
622660
},
623661
},

0 commit comments

Comments
 (0)