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
funcGetAttrOrNil(selfObject, keystring) (resObject){
128+
deferfunc(){
129+
ifr:=recover(); r!=nil{
130+
ifIsException(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
ifI, 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
returnm
5454
}
55+
56+
// Calls a named method of a module
57+
func (m*Module) Call(namestring, argsTuple, kwargsStringDict) Object{
58+
returnCall(m.M__getattribute__(name), args, kwargs)
59+
}
60+
61+
// Get an attribute from the module
62+
func (m*Module) M__getattribute__(namestring) 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+
returnres
68+
}
69+
70+
func (m*Module) M__setattr__(namestring, valueObject) Object{
71+
m.Globals[name] =value
72+
returnNone
73+
}
74+
75+
// Interfaces
76+
var_I__getattribute__= (*Module)(nil)
77+
var_I__setattr__= (*Module)(nil)

0 commit comments

Comments
(0)