Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion py/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func RunSrc(ctx Context, pySrc string, pySrcDesc string, inModule interface{}) (
//
// If inModule is a *Module, then the code is run in that module.
//
// If inModule is nil, the code is run in a new __main__ module (and the new Module is returned).
// If inModule is nil or a nil *Module, the code is run in a new __main__ module (and the new Module is returned).
//
// If inModule is a string, the code is run in a new module with the given name (and the new Module is returned).
func RunCode(ctx Context, code *Code, codeDesc string, inModule interface{}) (*Module, error) {
Expand All @@ -162,6 +162,10 @@ func RunCode(ctx Context, code *Code, codeDesc string, inModule interface{}) (*M
case nil:
createNew = true
case *Module:
if mod == nil {
createNew = true
break
}
_, err = ctx.RunCode(code, mod.Globals, mod.Globals, nil)
module = mod
default:
Expand Down
54 changes: 54 additions & 0 deletions py/run_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2026 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package py_test

import (
"os"
"path/filepath"
"testing"

"github.com/go-python/gpython/py"
_ "github.com/go-python/gpython/stdlib"
)

func TestRunWithNilModulePointer(t *testing.T) {
for _, entry := range []string{"RunCode", "RunSrc", "RunFile"} {
t.Run(entry, func(t *testing.T) {
ctx := py.NewContext(py.DefaultContextOpts())
defer ctx.Close()
src := "value = 42\n"
var module *py.Module
var err error
switch entry {
case "RunCode":
var code *py.Code
code, err = py.Compile(src, "<test>", py.ExecMode, 0, true)
if err == nil {
module, err = py.RunCode(ctx, code, "<test>", module)
}
case "RunSrc":
module, err = py.RunSrc(ctx, src, "<test>", module)
case "RunFile":
path := filepath.Join(t.TempDir(), "test.py")
if err = os.WriteFile(path, []byte(src), 0600); err == nil {
module, err = py.RunFile(ctx, filepath.Base(path), py.CompileOpts{CurDir: filepath.Dir(path)}, module)
}
}
if err != nil {
t.Fatal(err)
}
if module == nil || module.Globals["value"] != py.Int(42) {
t.Fatalf("expected a new module containing value = 42, got %v", module)
}
reused, err := py.RunSrc(ctx, "value += 1", "<reuse>", module)
if err != nil {
t.Fatal(err)
}
if reused != module || module.Globals["value"] != py.Int(43) {
t.Fatal("expected the existing module and globals to be reused")
}
})
}
}