monty

package module
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 13 Imported by: 1

README

gomonty

gomonty is an experimental standalone repository for the Go bindings to Monty. The Go package keeps the copied binding API and package name monty, while the Rust FFI crate is split out so it can build against upstream Monty through pinned Cargo git dependencies.

Documentation: https://pkg.go.dev/github.com/ewhauser/gomonty

Status

  • Experimental.
  • Go module path: github.com/ewhauser/gomonty
  • Go bindings are cgo-free and use purego with bundled shared libraries
  • Rust FFI crate: crates/monty-go-ffi
  • Upstream Monty source: pinned in the root Cargo.toml
  • Native shared libraries: checked into internal/ffi/lib/<target>
  • Generated header: checked into internal/ffi/include/monty_go_ffi.h
  • Alpine/musl builds use a separate musl Go build tag and musl-specific shared libraries

Tagged source trees must already contain the native shared libraries required by the runtime loader. GitHub release assets are optional convenience copies, not the source of truth for Go module consumers.

Repository Layout

  • *.go, vfs/, internal/ffi/: copied Go bindings adapted to the root module layout
  • go/README.md: consumer-facing Go API notes and examples carried over from the source repo
  • examples/: standalone example module for local consumption examples
  • crates/monty-go-ffi/: copied Rust C ABI crate
  • scripts/build-go-ffi.sh <target-triple>: builds one target shared library into internal/ffi/lib/...

Build Notes

The Go package is cgo-free. It uses purego to load a bundled shared library for the current target from internal/ffi/lib/<target>.

On first use, the loader extracts the embedded shared library to os.UserCacheDir() with an os.TempDir() fallback, then opens it with the platform loader.

Default Linux builds target the GNU/glibc shared libraries. Alpine and other musl-based Linux builds must opt into the musl family with the musl Go build tag.

The verify workflow runs CGO_ENABLED=0 Go tests on native Linux, macOS, and Windows runners. Musl shared libraries are build-verified rather than executed in CI.

To build or refresh the shared library for the current host:

scripts/build-go-ffi.sh aarch64-apple-darwin
CGO_ENABLED=0 go test ./...

Requirements:

  • Go 1.25+
  • Rust toolchain
  • Python available on PATH, or PYO3_PYTHON set explicitly
  • cbindgen only when regenerating internal/ffi/include/monty_go_ffi.h

For repeat builds where the checked-in header does not need to change, set MONTY_GO_FFI_SKIP_HEADER=1.

For Alpine or another musl-based Linux environment:

scripts/build-go-ffi.sh x86_64-unknown-linux-musl
go test -tags musl ./...

Consumer Example

For normal consumers, the intended path is to depend on a tagged version of this repo whose source tree already contains the native shared library for the consumer's target platform.

Add the module:

go get github.com/ewhauser/gomonty@latest

Or in go.mod:

require github.com/ewhauser/gomonty vX.Y.Z

Then import and use it:

package main

import (
	"context"
	"fmt"
	"log"

	monty "github.com/ewhauser/gomonty"
)

func main() {
	runner, err := monty.New("40 + 2", monty.CompileOptions{
		ScriptName: "example.py",
	})
	if err != nil {
		log.Fatal(err)
	}

	value, err := runner.Run(context.Background(), monty.RunOptions{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(value.Raw())
}

The same example lives in examples/cmd/example. To run it from this repo checkout:

cd examples
CGO_ENABLED=0 go run ./cmd/example

If you are consuming a branch, local checkout, or unreleased commit instead of a prepared tag, you may need to build or refresh the shared library for your platform first:

scripts/build-go-ffi.sh aarch64-apple-darwin

For Alpine or musl-based Linux consumers, also add the musl build tag when building or testing your application:

go build -tags musl ./...

Benchmarks

The Go benchmark suite mirrors the current upstream Monty benchmark cases so the two projects exercise the same scripts and expected outputs. The shared kitchen-sink workload is copied into testdata/bench_kitchen_sink.py.

With a host shared library built, run the local Go-only benchmarks with:

CGO_ENABLED=0 go test -run '^$' -bench BenchmarkMonty -benchmem

This covers the parse-once/repeated-run benchmark cases plus BenchmarkMontyEndToEnd for parse-and-run in the loop.

There are also Go-specific benchmark suites for wrapper overhead:

CGO_ENABLED=0 go test -run '^$' -bench BenchmarkMontyCallbacks -benchmem
CGO_ENABLED=0 go test -run '^$' -bench BenchmarkMontyDecompose -benchmem

These add:

  • callback-heavy runs with repeated external function and OS handler calls
  • low-level decomposition benchmarks for compile-only, dump/load, start-to-first-progress, name lookup, call resume, and pending resume paths

To capture CPU and allocation profiles for the representative hot paths, run:

scripts/profile-benchmarks.sh

By default the script writes profiles and pprof -top summaries to /tmp/gomonty-bench-profiles for:

  • BenchmarkMontyEndToEnd
  • BenchmarkMonty/list_append_int
  • BenchmarkMontyCallbacks/external_loop

To compare gomonty against a local upstream Monty checkout on the same host, run:

python3 scripts/compare-benchmarks.py --upstream ../monty

The comparison script:

  • runs the Go benchmark suite and aggregates the median ns/op across three runs
  • runs the upstream Criterion __monty benchmarks
  • sets PYO3_PYTHON for the upstream run if the upstream checkout still expects a local .venv/bin/python3
  • prints a Markdown table suitable for pasting back into this README

Current sample comparison from 2026-03-24 on darwin/arm64 (Apple M3 Max), measured from gomonty dddae9616d8b-dirty against upstream Monty 982709bd52b1-dirty:

Case gomonty raw monty Ratio
add_two 2.916 us 721 ns 4.04x
list_append 3.204 us 853 ns 3.76x
loop_mod_13 42.157 us 37.906 us 1.11x
kitchen_sink 7.942 us 4.035 us 1.97x
func_call_kwargs 3.501 us 1.045 us 3.35x
list_append_str 14.200 ms 14.557 ms 0.98x
list_append_int 4.855 ms 4.976 ms 0.98x
fib 20.547 ms 21.204 ms 0.97x
list_comp 32.750 us 29.786 us 1.10x
dict_comp 78.033 us 69.671 us 1.12x
empty_tuples 2.664 ms 2.794 ms 0.95x
pair_tuples 8.917 ms 9.111 ms 0.98x
end_to_end 5.240 us 1.891 us 2.77x

These numbers are host-specific. They compare the same benchmark scripts, but the Go side uses testing.B while upstream uses Criterion.

Fuzzing

The repo also includes Go fuzz targets for:

  • FuzzValueJSON: pure-Go value wire-format decoding and normalization
  • FuzzCompileAndRun: arbitrary source strings compiled and executed with tight resource limits
  • FuzzLoadRunner: arbitrary bytes fed through LoadRunner, including valid dumped-runner seeds

Run a short fuzzing pass with:

CGO_ENABLED=0 go test -run '^$' -fuzz FuzzValueJSON -fuzztime=10s .
CGO_ENABLED=0 go test -run '^$' -fuzz FuzzCompileAndRun -fuzztime=10s .
CGO_ENABLED=0 go test -run '^$' -fuzz FuzzLoadRunner -fuzztime=10s .

The native runner fuzzers require a supported host shared library and run with CGO_ENABLED=0. FuzzValueJSON remains pure Go.

Upstream Overrides

The default build uses pinned git dependencies on https://github.com/pydantic/monty.git. For local development against a sibling checkout, you can temporarily override them with a Cargo patch:

[patch."https://github.com/pydantic/monty.git"]
monty = { path = "../monty/crates/monty" }
monty_type_checking = { path = "../monty/crates/monty-type-checking" }

See RELEASING.md for bumping the upstream pin and for the protected-branch release flow: make release opens the release-prep PR, then make publish-release VERSION=vX.Y.Z tags merged main, creates the GitHub release, and warms the Go module proxy.

Documentation

Overview

Package monty exposes cgo-free Go bindings for the Monty sandboxed Python interpreter.

The package provides compiled runner and REPL APIs, typed value conversion, host callback dispatch, and low-level pause/resume snapshots. It embeds the platform-specific shared library needed by the bindings and loads it with purego, so normal Go module consumers do not need a local C toolchain.

For Go-owned filesystem and environment callbacks, use the companion vfs package.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrClosed reports that a handle-backed object no longer owns a native handle.
	ErrClosed = errors.New("monty handle is closed")
	// ErrConcurrentUse reports that the same handle-backed object is already being used.
	ErrConcurrentUse = errors.New("monty handle is already in use")
)

Functions

func LoadReplSnapshot

func LoadReplSnapshot(data []byte) (Progress, *Repl, error)

LoadReplSnapshot restores a serialized REPL snapshot and also returns a base REPL handle that can be used to abandon the in-flight snippet.

Types

type Call

type Call struct {
	FunctionName string
	Args         []Value
	Kwargs       Dict
	CallID       uint32
	IsMethodCall bool
}

Call describes an external function or method invocation from Monty.

type CompileOptions

type CompileOptions struct {
	ScriptName     string
	Inputs         []string
	TypeCheck      bool
	TypeCheckStubs string
}

CompileOptions configures runner compilation.

type Complete

type Complete struct {
	Output     Value
	ScriptName string
	IsRepl     bool
}

Complete is a finished execution result.

type Dataclass

type Dataclass struct {
	Name       string                   `json:"name"`
	TypeID     uint64                   `json:"type_id"`
	FieldNames []string                 `json:"field_names"`
	Attrs      Dict                     `json:"attrs"`
	Frozen     bool                     `json:"frozen"`
	Methods    map[string]MethodHandler `json:"-"`
}

Dataclass is the explicit host-side dataclass value shape.

Methods are host-only metadata and are intentionally omitted from the wire format so Rust never stores Go function pointers or opaque Go values.

type Date

type Date struct {
	Year  int32 `json:"year"`
	Month uint8 `json:"month"`
	Day   uint8 `json:"day"`
}

Date represents a Python datetime.date value.

type DateTime

type DateTime struct {
	Year          int32   `json:"year"`
	Month         uint8   `json:"month"`
	Day           uint8   `json:"day"`
	Hour          uint8   `json:"hour"`
	Minute        uint8   `json:"minute"`
	Second        uint8   `json:"second"`
	Microsecond   uint32  `json:"microsecond"`
	OffsetSeconds *int32  `json:"offset_seconds,omitempty"`
	TimezoneName  *string `json:"timezone_name,omitempty"`
}

DateTime represents a Python datetime.datetime value.

type Dict

type Dict []Pair

Dict preserves insertion order and non-string keys.

type Exception

type Exception struct {
	Type string  `json:"exc_type"`
	Arg  *string `json:"arg,omitempty"`
}

Exception is both a first-class Monty value and the explicit exception shape returned by host callbacks.

func (Exception) Error

func (e Exception) Error() string

Error formats the exception as `Type: message`.

func (Exception) FromError

func (e Exception) FromError(err error) Exception

FromError converts an arbitrary Go error into an explicit exception shape.

type ExternalFunction

type ExternalFunction func(context.Context, Call) (Result, error)

ExternalFunction handles a host external function callback.

type FeedOptions

type FeedOptions struct {
	Inputs    map[string]Value
	Functions map[string]ExternalFunction
	OS        OSHandler
	Print     PrintCallback
}

FeedOptions configures the high-level REPL helper loop.

type FeedStartOptions

type FeedStartOptions struct {
	Inputs map[string]Value
}

FeedStartOptions configures low-level REPL snippet execution.

type Frame

type Frame struct {
	Filename     string  `json:"filename"`
	Line         uint32  `json:"line"`
	Column       uint32  `json:"column"`
	EndLine      uint32  `json:"end_line"`
	EndColumn    uint32  `json:"end_column"`
	FunctionName *string `json:"function_name,omitempty"`
	SourceLine   *string `json:"source_line,omitempty"`
}

Frame is a structured traceback frame returned by runtime and syntax errors.

type FrozenSet

type FrozenSet []Value

FrozenSet is the explicit frozenset shape used by the bindings.

type Function

type Function struct {
	Name      string  `json:"name"`
	Docstring *string `json:"docstring,omitempty"`
}

Function is the explicit external-function value used during name lookup.

type FutureSnapshot

type FutureSnapshot struct {
	// contains filtered or unexported fields
}

FutureSnapshot is a paused future-resolution state.

func (*FutureSnapshot) Dump

func (s *FutureSnapshot) Dump() ([]byte, error)

Dump serializes the current future snapshot.

func (*FutureSnapshot) PendingCallIDs

func (s *FutureSnapshot) PendingCallIDs() []uint32

PendingCallIDs returns the unresolved call IDs for the future snapshot.

func (*FutureSnapshot) ResumeResults

func (s *FutureSnapshot) ResumeResults(ctx context.Context, results map[uint32]Result) (Progress, error)

ResumeResults resumes a future snapshot with zero or more resolved call IDs.

type MethodHandler

type MethodHandler = ExternalFunction

MethodHandler handles a host dataclass method callback.

type NameLookupSnapshot

type NameLookupSnapshot struct {
	VariableName string
	// contains filtered or unexported fields
}

NameLookupSnapshot is a paused unresolved-name lookup.

func (*NameLookupSnapshot) Dump

func (s *NameLookupSnapshot) Dump() ([]byte, error)

Dump serializes the current name-lookup snapshot.

func (*NameLookupSnapshot) ResumeUndefined

func (s *NameLookupSnapshot) ResumeUndefined(ctx context.Context) (Progress, error)

ResumeUndefined resumes a name lookup as undefined.

func (*NameLookupSnapshot) ResumeValue

func (s *NameLookupSnapshot) ResumeValue(ctx context.Context, value Value) (Progress, error)

ResumeValue resumes a name lookup with a resolved value.

type NamedTuple

type NamedTuple struct {
	TypeName   string   `json:"type_name"`
	FieldNames []string `json:"field_names"`
	Values     []Value  `json:"values"`
}

NamedTuple carries the explicit named-tuple wire shape.

type OSCall

type OSCall struct {
	Function OSFunction
	Args     []Value
	Kwargs   Dict
	CallID   uint32
}

OSCall describes an OS-level callback requested by Monty.

type OSFunction

type OSFunction string

OSFunction names a host OS callback that Monty requested.

const (
	OSPathExists     OSFunction = "Path.exists"
	OSPathIsFile     OSFunction = "Path.is_file"
	OSPathIsDir      OSFunction = "Path.is_dir"
	OSPathIsSymlink  OSFunction = "Path.is_symlink"
	OSPathReadText   OSFunction = "Path.read_text"
	OSPathReadBytes  OSFunction = "Path.read_bytes"
	OSPathWriteText  OSFunction = "Path.write_text"
	OSPathWriteBytes OSFunction = "Path.write_bytes"
	OSPathMkdir      OSFunction = "Path.mkdir"
	OSPathUnlink     OSFunction = "Path.unlink"
	OSPathRmdir      OSFunction = "Path.rmdir"
	OSPathIterdir    OSFunction = "Path.iterdir"
	OSPathStat       OSFunction = "Path.stat"
	OSPathRename     OSFunction = "Path.rename"
	OSPathResolve    OSFunction = "Path.resolve"
	OSPathAbsolute   OSFunction = "Path.absolute"
	OSGetenv         OSFunction = "os.getenv"
	OSGetEnviron     OSFunction = "os.environ"
)

type OSHandler

type OSHandler func(context.Context, OSCall) (Result, error)

OSHandler handles a host OS callback.

type Pair

type Pair struct {
	Key   Value `json:"key"`
	Value Value `json:"value"`
}

Pair preserves insertion order and non-string keys for dict-like values.

type Path

type Path string

Path is an explicit Monty path value.

type PrintCallback

type PrintCallback func(stream string, text string)

PrintCallback receives aggregated stdout text emitted during each execution step.

func WriterPrintCallback

func WriterPrintCallback(w io.Writer) PrintCallback

WriterPrintCallback writes captured stdout to an io.Writer.

type Progress

type Progress interface {
	// contains filtered or unexported methods
}

Progress is the low-level pause/resume execution interface.

func LoadSnapshot

func LoadSnapshot(data []byte) (Progress, error)

LoadSnapshot restores a serialized non-REPL or REPL snapshot without an owner REPL.

type Repl

type Repl struct {
	// contains filtered or unexported fields
}

Repl is a stateful Monty REPL session.

func NewRepl

func NewRepl(opts ReplOptions) (*Repl, error)

NewRepl constructs an empty REPL session.

func (*Repl) Dump

func (r *Repl) Dump() ([]byte, error)

Dump serializes the REPL session.

func (*Repl) FeedRun

func (r *Repl) FeedRun(ctx context.Context, code string, opts FeedOptions) (Value, error)

FeedRun executes a REPL snippet through the high-level host callback loop.

func (*Repl) FeedStart

func (r *Repl) FeedStart(ctx context.Context, code string, opts FeedStartOptions) (Progress, error)

FeedStart begins low-level REPL snippet execution.

type ReplOptions

type ReplOptions struct {
	ScriptName string
	Limits     *ResourceLimits
}

ReplOptions configures REPL construction.

type ResourceLimits

type ResourceLimits struct {
	MaxAllocations    int
	MaxDuration       time.Duration
	MaxMemory         int
	GCInterval        int
	MaxRecursionDepth int
}

ResourceLimits controls Monty execution limits.

A zero field value leaves that limit unset.

type Result

type Result struct {
	// contains filtered or unexported fields
}

Result is the explicit host callback result union.

The zero value is treated as `Return(None())`, which keeps simple handlers ergonomic while preserving an explicit pending/exception path.

func Pending

func Pending(waiter Waiter) Result

Pending constructs a callback result backed by a waiter.

func Raise

func Raise(exception Exception) Result

Raise constructs a callback result that raises an explicit exception.

func Return

func Return(value Value) Result

Return constructs a successful callback result.

func (Result) IsPending

func (r Result) IsPending() bool

IsPending reports whether the result is pending.

func (Result) Raised

func (r Result) Raised() (*Exception, bool)

Raised returns the explicit exception payload for an exception result.

func (Result) Value

func (r Result) Value() Value

Value returns the success value for a return result.

func (Result) Waiter

func (r Result) Waiter() Waiter

Waiter returns the waiter attached to a pending result.

type RunOptions

type RunOptions struct {
	Inputs    map[string]Value
	Functions map[string]ExternalFunction
	OS        OSHandler
	Print     PrintCallback
	Limits    *ResourceLimits
}

RunOptions configures the high-level runner helper loop.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner is the compiled runner entrypoint for Monty code.

func LoadRunner

func LoadRunner(data []byte) (*Runner, error)

LoadRunner restores a serialized runner.

func New

func New(code string, opts CompileOptions) (*Runner, error)

New compiles Monty code into a reusable runner.

func (*Runner) Dump

func (r *Runner) Dump() ([]byte, error)

Dump serializes the runner.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, opts RunOptions) (Value, error)

Run executes the runner through the high-level host callback loop.

Example
package main

import (
	"context"
	"fmt"

	monty "github.com/ewhauser/gomonty"
)

func main() {
	runner, err := monty.New("40 + 2", monty.CompileOptions{
		ScriptName: "example.py",
	})
	if err != nil {
		panic(err)
	}

	value, err := runner.Run(context.Background(), monty.RunOptions{})
	if err != nil {
		panic(err)
	}

	fmt.Println(value.Raw())
}
Output:
42

func (*Runner) Start

func (r *Runner) Start(ctx context.Context, opts StartOptions) (Progress, error)

Start begins low-level runner execution.

func (*Runner) TypeCheck

func (r *Runner) TypeCheck(prefix string) error

TypeCheck runs static type checking on the compiled runner.

type RuntimeError

type RuntimeError struct {
	Frames []Frame
	// contains filtered or unexported fields
}

RuntimeError is raised for runtime failures and exposes traceback frames.

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

func (*RuntimeError) TracebackString

func (e *RuntimeError) TracebackString() string

type Set

type Set []Value

Set is the explicit set shape used by the bindings.

type Snapshot

type Snapshot struct {
	FunctionName string
	Args         []Value
	Kwargs       Dict
	CallID       uint32
	IsOSFunction bool
	IsMethodCall bool
	// contains filtered or unexported fields
}

Snapshot is a paused external function, method call, or OS call.

func (*Snapshot) Dump

func (s *Snapshot) Dump() ([]byte, error)

Dump serializes the current snapshot.

func (*Snapshot) ResumeException

func (s *Snapshot) ResumeException(ctx context.Context, exception Exception) (Progress, error)

ResumeException resumes a function or OS snapshot by raising an exception.

func (*Snapshot) ResumePending

func (s *Snapshot) ResumePending(ctx context.Context) (Progress, error)

ResumePending resumes a function or OS snapshot with a pending future.

func (*Snapshot) ResumeReturn

func (s *Snapshot) ResumeReturn(ctx context.Context, value Value) (Progress, error)

ResumeReturn resumes a function or OS snapshot with a return value.

type StartOptions

type StartOptions struct {
	Inputs map[string]Value
	Limits *ResourceLimits
}

StartOptions configures low-level runner execution.

type StatResult

type StatResult struct {
	Mode  int64
	Ino   int64
	Dev   int64
	Nlink int64
	UID   int64
	GID   int64
	Size  int64
	Atime float64
	Mtime float64
	Ctime float64
}

StatResult is the explicit host helper for `os.stat_result`-compatible values.

type SyntaxError

type SyntaxError struct {
	// contains filtered or unexported fields
}

SyntaxError is raised for parse or compile failures.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

func (*SyntaxError) TracebackString

func (e *SyntaxError) TracebackString() string

type TimeDelta

type TimeDelta struct {
	Days         int32 `json:"days"`
	Seconds      int32 `json:"seconds"`
	Microseconds int32 `json:"microseconds"`
}

TimeDelta represents a Python datetime.timedelta value.

type TimeZone

type TimeZone struct {
	OffsetSeconds int32   `json:"offset_seconds"`
	Name          *string `json:"name,omitempty"`
}

TimeZone represents a Python datetime.timezone fixed-offset value.

type Tuple

type Tuple []Value

Tuple is the explicit tuple shape used by the bindings.

type TypingError

type TypingError struct {
	// contains filtered or unexported fields
}

TypingError is raised for static type-check failures and can re-render the diagnostics using the formatter strings supported by Rust.

func (*TypingError) Display

func (e *TypingError) Display(format string, color bool) string

Display renders the typing diagnostics using one of Rust's formatter names: `full`, `concise`, `azure`, `json`, `jsonlines`, `rdjson`, `pylint`, `gitlab`, or `github`.

func (*TypingError) Error

func (e *TypingError) Error() string

func (*TypingError) TracebackString

func (e *TypingError) TracebackString() string

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value is the public tagged union used by the Go bindings.

Primitive Go values round-trip directly where safe: `nil`, `bool`, signed integers, `float64`, `string`, and `[]byte`. Non-native Monty shapes remain explicit through helper structs such as Dict, Tuple, NamedTuple, Path, Dataclass, Function, and Exception.

func BigInt

func BigInt(value *big.Int) Value

BigInt returns an arbitrary-precision integer value.

func Bool

func Bool(value bool) Value

Bool returns a bool value.

func Bytes

func Bytes(value []byte) Value

Bytes returns a bytes value.

func CycleValue

func CycleValue(value string) Value

CycleValue returns an output-only cycle placeholder.

func DataclassValue

func DataclassValue(value Dataclass) Value

DataclassValue returns a dataclass value.

func DateTimeValue

func DateTimeValue(dt DateTime) Value

DateTimeValue returns a datetime value.

func DateValue

func DateValue(date Date) Value

DateValue returns a date value.

func DictValue

func DictValue(items Dict) Value

DictValue returns a dict value.

func Ellipsis

func Ellipsis() Value

Ellipsis returns the Python Ellipsis value.

func ExceptionValue

func ExceptionValue(exception Exception) Value

ExceptionValue returns an exception value.

func Float

func Float(value float64) Value

Float returns a float value.

func FrozenSetValue

func FrozenSetValue(items FrozenSet) Value

FrozenSetValue returns a frozenset value.

func FunctionValue

func FunctionValue(function Function) Value

FunctionValue returns an external-function value.

func Int

func Int(value int64) Value

Int returns a signed integer value.

func List

func List(items ...Value) Value

List returns a list value.

func MustValueOf

func MustValueOf(value any) Value

MustValueOf converts a Go value and panics if conversion fails.

func NamedTupleValue

func NamedTupleValue(value NamedTuple) Value

NamedTupleValue returns a named-tuple value.

func None

func None() Value

None returns the Python None value.

func PathValue

func PathValue(path Path) Value

PathValue returns a path value.

func ReprValue

func ReprValue(value string) Value

ReprValue returns an output-only repr placeholder.

func SetValue

func SetValue(items Set) Value

SetValue returns a set value.

func String

func String(value string) Value

String returns a string value.

func TimeDeltaValue

func TimeDeltaValue(td TimeDelta) Value

TimeDeltaValue returns a timedelta value.

func TimeZoneValue

func TimeZoneValue(tz TimeZone) Value

TimeZoneValue returns a timezone value.

func TupleValue

func TupleValue(items ...Value) Value

TupleValue returns a tuple value.

func ValueOf

func ValueOf(value any) (Value, error)

ValueOf converts a supported Go value into a Monty Value.

func (Value) Dataclass

func (v Value) Dataclass() (Dataclass, bool)

Dataclass returns the dataclass payload if present.

func (Value) Date

func (v Value) Date() (Date, bool)

Date returns the date payload if present.

func (Value) DateTime

func (v Value) DateTime() (DateTime, bool)

DateTime returns the datetime payload if present.

func (Value) Exception

func (v Value) Exception() (Exception, bool)

Exception returns the exception payload if present.

func (Value) Function

func (v Value) Function() (Function, bool)

Function returns the function payload if present.

func (Value) Kind

func (v Value) Kind() ValueKind

Kind reports the value variant.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

func (Value) Raw

func (v Value) Raw() any

Raw exposes the underlying variant payload.

func (Value) StatResult

func (v Value) StatResult() (StatResult, bool)

StatResult returns a stat-result payload when the value is a compatible named tuple.

func (Value) String

func (v Value) String() string

func (Value) TimeDelta

func (v Value) TimeDelta() (TimeDelta, bool)

TimeDelta returns the timedelta payload if present.

func (Value) TimeZone

func (v Value) TimeZone() (TimeZone, bool)

TimeZone returns the timezone payload if present.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the stable Rust/Go wire schema for values.

type ValueKind

type ValueKind string

ValueKind identifies the Monty value variant held by a Value.

type Waiter

type Waiter interface {
	Wait(context.Context) Result
}

Waiter represents a pending external result that will be resolved later.

Directories

Path Synopsis
internal
ffi
Package vfs adapts Go-defined filesystems and environments into Monty OS handlers.
Package vfs adapts Go-defined filesystems and environments into Monty OS handlers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL