MCPcopy Index your code
hub / github.com/go-python/gopy / genStructInit

Method genStructInit

bind/gen_struct.go:38–161  ·  view source on GitHub ↗
(s *Struct)

Source from the content-addressed store, hash-verified

36}
37
38func (g *pyGen) genStructInit(s *Struct) {
39 pkgname := g.cfg.Name
40 qNm := s.GoName()
41 // strNm := s.obj.Name()
42
43 numFields := s.Struct().NumFields()
44
45 g.pywrap.Printf("def __init__(self, *args, **kwargs):\n")
46 g.pywrap.Indent()
47 g.pywrap.Printf(`"""
48handle=A Go-side object is always initialized with an explicit handle=arg
49otherwise parameters can be unnamed in order of field names or named fields
50in which case a new Go object is constructed first
51"""
52`)
53 g.pywrap.Printf("if len(kwargs) == 1 and 'handle' in kwargs:\n")
54 g.pywrap.Indent()
55 g.pywrap.Printf("self.handle = kwargs['handle']\n")
56 g.pywrap.Printf("_%s.IncRef(self.handle)\n", g.pypkgname)
57 g.pywrap.Outdent()
58 g.pywrap.Printf("elif len(args) == 1 and isinstance(args[0], go.GoClass):\n")
59 g.pywrap.Indent()
60 g.pywrap.Printf("self.handle = args[0].handle\n")
61 g.pywrap.Printf("_%s.IncRef(self.handle)\n", g.pypkgname)
62 g.pywrap.Outdent()
63 g.pywrap.Printf("else:\n")
64 g.pywrap.Indent()
65 g.pywrap.Printf("self.handle = _%s.%s_CTor()\n", pkgname, s.ID())
66 g.pywrap.Printf("_%s.IncRef(self.handle)\n", g.pypkgname)
67
68 for i := 0; i < numFields; i++ {
69 f := s.Struct().Field(i)
70 if _, err := isPyCompatField(f); err != nil {
71 continue
72 }
73 // NOTE: this will accept int args for any handles / object fields so
74 // some kind of additional type-checking logic to prevent that in a way
75 // that also allows valid handles to be used as required. This is
76 // achieved in the per-field setters (see below) with checks to ensure
77 // that a struct field that is a gopy managed object is only
78 // assigned gopy managed objects. Fields of basic types (e.g int, string)
79 // etc can be assigned to directly.
80 g.pywrap.Printf("if %[1]d < len(args):\n", i)
81 g.pywrap.Indent()
82 g.pywrap.Printf("self.%s = args[%d]\n", f.Name(), i)
83 g.pywrap.Outdent()
84 g.pywrap.Printf("if %[1]q in kwargs:\n", f.Name())
85 g.pywrap.Indent()
86 g.pywrap.Printf("self.%[1]s = kwargs[%[1]q]\n", f.Name())
87 g.pywrap.Outdent()
88 }
89 g.pywrap.Outdent()
90 g.pywrap.Outdent()
91
92 g.pywrap.Printf("def __del__(self):\n")
93 g.pywrap.Indent()
94 g.pywrap.Printf("_%s.DecRef(self.handle)\n", g.pypkgname)
95 g.pywrap.Outdent()

Callers 1

genStructMethod · 0.95

Calls 10

genStringerCallMethod · 0.95
isPyCompatFieldFunction · 0.85
isStringerFunction · 0.85
StructMethod · 0.80
PrintfMethod · 0.80
IndentMethod · 0.80
OutdentMethod · 0.80
GoNameMethod · 0.65
IDMethod · 0.65
NameMethod · 0.45

Tested by

no test coverage detected