-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathmodule.go
95 lines (83 loc) · 1.86 KB
/
module.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Module objects
package py
import (
"fmt"
)
var (
// Registry of installed modules
modules = make(map[string]*Module)
// Builtin module
Builtins *Module
// this should be the frozen module importlib/_bootstrap.py generated
// by Modules/_freeze_importlib.c into Python/importlib.h
Importlib *Module
)
// A python Module object
type Module struct {
Name string
Doc string
Globals StringDict
// dict Dict
}
var ModuleType = NewType("module", "module object")
// Type of this object
func (o *Module) Type() *Type {
return ModuleType
}
// Get the Dict
func (m *Module) GetDict() StringDict {
return m.Globals
}
// Define a new module
func NewModule(name, doc string, methods []*Method, globals StringDict) *Module {
m := &Module{
Name: name,
Doc: doc,
Globals: globals.Copy(),
}
// Insert the methods into the module dictionary
for _, method := range methods {
m.Globals[method.Name] = method
}
// Set some module globals
m.Globals["__name__"] = String(name)
m.Globals["__doc__"] = String(doc)
m.Globals["__package__"] = None
// Register the module
modules[name] = m
// Make a note of some modules
switch name {
case "builtins":
Builtins = m
case "importlib":
Importlib = m
}
fmt.Printf("Registering module %q\n", name)
return m
}
// Gets a module
func GetModule(name string) (*Module, error) {
m, ok := modules[name]
if !ok {
return nil, ExceptionNewf(ImportError, "Module %q not found", name)
}
return m, nil
}
// Gets a module or panics
func MustGetModule(name string) *Module {
m, err := GetModule(name)
if err != nil {
panic(err)
}
return m
}
// Calls a named method of a module
func (m *Module) Call(name string, args Tuple, kwargs StringDict) (Object, error) {
attr, err := GetAttrString(m, name)
if err != nil {
return nil, err
}
return Call(attr, args, kwargs)
}
// Interfaces
var _ IGetDict = (*Module)(nil)