8000 Make modules have attributes and call methods in them · go-python/gpython@c1949ed · GitHub
[go: up one dir, main page]

Skip to content

Commit c1949ed

Browse files
committed
Make modules have attributes and call methods in them
1 parent 858b973 commit c1949ed

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

py/internal.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,18 @@ func SetItem(self Object, key Object, value Object) Object {
125125

126126
// GetAttrOrNil - returns the result nil if attribute not found
127127
func GetAttrOrNil(self Object, key string) (res Object) {
128+
defer func() {
129+
if r := recover(); r != nil {
130+
if IsException(AttributeError, r) {
131+
// AttributeError caught - return nil
132+
res = nil
133+
} else {
134+
// Propagate the exception
135+
panic(r)
136+
}
137+
}
138+
}()
139+
128140
// Call __getattribute unconditionally if it exists
129141
if I, ok := self.(I__getattribute__); ok {
130142
res = I.M__getattribute__(key)

py/module.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,26 @@ func NewModule(name, doc string, methods []*Method, globals StringDict) *Module
5252
fmt.Printf("Registering module %q\n", name)
5353
return m
5454
}
55+
56+
// Calls a named method of a module
57+
func (m *Module) Call(name string, args Tuple, kwargs StringDict) Object {
58+
return Call(m.M__getattribute__(name), args, kwargs)
59+
}
60+
61+
// Get an attribute from the module
62+
func (m *Module) M__getattribute__(name string) Object {
63+
res, ok := m.Globals[name]
64+
if !ok {
65+
panic(ExceptionNewf(AttributeError, "module '%s' has no attribute '%s'", m.Name, name))
66+
}
67+
return res
68+
}
69+
70+
func (m *Module) M__setattr__(name string, value Object) Object {
71+
m.Globals[name] = value
72+
return None
73+
}
74+
75+
// Interfaces
76+
var _ I__getattribute__ = (*Module)(nil)
77+
var _ I__setattr__ = (*Module)(nil)

0 commit comments

Comments
 (0)
0