@@ -111,32 +111,48 @@ var (
111111 Compile func (src , srcDesc string , mode CompileMode , flags int , dont_inherit bool ) (* Code , error )
112112)
113113
114- // Convenience function that resolves then executes the given file pathname in a new module.
115- // If moduleName is nil, "__main__" is used
116- func RunInNewModule (
117- ctx Ctx ,
118- pathname string ,
119- opts CompileOpts ,
120- moduleName string ,
121- ) (* Module , error ) {
114+ // Resolves the given pathname, compiles as needed, and runs that code in the given module, returning the Module to indicate success.
115+ // If inModule is a *Module, then the code is run in that module.
116+ // If inModule is nil, the code is run in a new __main__ module (and the new Module is returned).
117+ // If inModule is a string, the code is run in a new module with the given name (and the new Module is returned).
118+ func RunFile (ctx Ctx , pathname string , opts CompileOpts , inModule interface {}) (* Module , error ) {
122119 out , err := ctx .ResolveAndCompile (pathname , opts )
123120 if err != nil {
124121 return nil , err
125122 }
126123
127- moduleImpl := ModuleImpl {
128- Info : ModuleInfo {
129- Name : moduleName ,
130- FileDesc : out .FileDesc ,
131- },
132- Code : out .Code ,
124+ var moduleName string
125+ createNew := false
126+ var module * Module
127+
128+ switch mod := inModule .(type ) {
129+
130+ case string :
131+ moduleName = mod
132+ createNew = true
133+ case nil :
134+ createNew = true
135+ case * Module :
136+ _ , err = ctx .RunCode (out .Code , mod .Globals , mod .Globals , nil )
137+ module = mod
138+ default :
139+ err = ExceptionNewf (TypeError , "unsupported module type: %v" , inModule )
133140 }
134141
135- return ctx .ModuleInit (& moduleImpl )
136- }
142+ if err == nil && createNew {
143+ moduleImpl := ModuleImpl {
144+ Info : ModuleInfo {
145+ Name : moduleName ,
146+ FileDesc : out .FileDesc ,
147+ },
148+ Code : out .Code ,
149+ }
150+ module , err = ctx .ModuleInit (& moduleImpl )
151+ }
152+
153+ if err != nil {
154+ return nil , err
155+ }
137156
138- // Convenience function that resolves then executes the given file pathname in a new __main__ module
139- func RunFile (ctx Ctx , pathname string , opts CompileOpts ) error {
140- _ , err := RunInNewModule (ctx , pathname , opts , "" )
141- return err
157+ return module , nil
142158}
0 commit comments