pyhost

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("python host is shut down")

ErrClosed is returned once shutdown has begun

View Source
var ErrForkedChild = errors.New("this call needs Go runtime threads, which do not exist in a child created by os.fork, use multiprocessing spawn or forkserver")

ErrForkedChild is returned for work that needs other OS threads inside a child created by os.fork

Functions

func Forked

func Forked() bool

Whether the process is a child created by os.fork from plugin code

Types

type Borrowed

type Borrowed uintptr

Borrowed passes an existing object pointer as an argument, the callee takes its own reference

type Exception

type Exception struct {
	Type    string
	Message string
}

Exception is a Go error raised into Python as the named class, a builtin name or module.Class

func (*Exception) Error

func (e *Exception) Error() string

type Func

type Func func(g *GIL, args []any, kwargs map[string]any) (any, error)

Func is a Go function callable from Python with arguments converted to Go values

type GIL

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

GIL proves the goroutine holds an attached thread state of the interpreter

func (*GIL) Attr

func (g *GIL) Attr(o uintptr, name string) (uintptr, error)

Attribute lookup, a new reference

func (*GIL) Call

func (g *GIL) Call(callable uintptr, args []any, kwargs map[string]any) (uintptr, error)

Calls callable with Go arguments, a new reference

func (*GIL) CallMethod

func (g *GIL) CallMethod(o uintptr, name string, args []any, kwargs map[string]any) (uintptr, error)

Calls a method by name, a new reference

func (*GIL) Callable

func (g *GIL) Callable(o uintptr) bool

Whether the object is callable

func (*GIL) Decref

func (g *GIL) Decref(o uintptr)

Decrements a reference obtained from this package

func (*GIL) DictDel

func (g *GIL) DictDel(d uintptr, key string)

Removes a string key from a dict, ignoring a missing key

func (*GIL) DictKeys

func (g *GIL) DictKeys(d uintptr) ([]string, error)

Keys of a dict as Go strings

func (*GIL) DictSet

func (g *GIL) DictSet(d uintptr, key string, value any) error

Stores a value in a dict under a string key

func (*GIL) Drain

func (g *GIL) Drain()

Drops every reference Go released since the last GIL entry, while the GIL is held

func (*GIL) ExceptionMatches

func (g *GIL) ExceptionMatches(err error, cls uintptr) (bool, error)

Reports whether err carries a Python exception that is an instance of cls, as an except clause naming cls would catch it

func (*GIL) ExceptionObject

func (g *GIL) ExceptionObject(err error) (uintptr, bool)

Borrowed exception object err carries, ok false when err holds no Python exception

func (*GIL) FromPython

func (g *GIL) FromPython(o uintptr) (any, error)

Converts a Python object to Go, containers by value and every other object as an owned *Ref

func (*GIL) HasAttr

func (g *GIL) HasAttr(o uintptr, name string) bool

Whether the object has the attribute, lookup errors count as absent the way hasattr reports them

func (*GIL) Host

func (g *GIL) Host() *Host

Host the token belongs to

func (*GIL) Import

func (g *GIL) Import(name string) (uintptr, error)

Imports a module, a new reference

func (*GIL) IsAwaitable

func (g *GIL) IsAwaitable(o uintptr) (bool, error)

Whether inspect.isawaitable reports the object awaitable

func (*GIL) IsInstance

func (g *GIL) IsInstance(o, cls uintptr) (bool, error)

Whether o is an instance of cls, with the exception of a failing check as the error

func (*GIL) IsNone

func (g *GIL) IsNone(o uintptr) bool

Whether the pointer is the None singleton

func (*GIL) IsSubclass

func (g *GIL) IsSubclass(o, cls uintptr) (bool, error)

Whether class o derives from cls, with the exception of a failing check as the error

func (*GIL) Iterate

func (g *GIL) Iterate(o uintptr, fn func(item uintptr) error) error

Calls fn with each item of the iterable as a borrowed pointer until the iterator ends or fn fails

func (*GIL) KindOf

func (g *GIL) KindOf(o uintptr) Kind

Builtin kind of an object, KindOther for every class outside the builtin scalars and containers

func (*GIL) Loop

func (g *GIL) Loop() uintptr

Borrowed event loop running on the host loop thread

func (*GIL) NewClass

func (g *GIL) NewClass(module, name string, bases []any, members map[string]any) (uintptr, error)

New class built by type(name, bases, namespace) whose RawFunc and Property members run Go code

func (*GIL) NewDocFunc

func (g *GIL) NewDocFunc(name, doc string, fn RawFunc) (uintptr, error)

Native callable named name with ml_doc set to doc, whose leading name(params) line becomes its text signature

func (*GIL) NewFunc

func (g *GIL) NewFunc(name string, fn Func) (uintptr, error)

Native callable named name that runs fn, a new reference

func (*GIL) NewObject

func (g *GIL) NewObject(impl Object) (uintptr, error)

Python object whose attribute lookup is answered by impl, a new reference

func (*GIL) NewRawFunc

func (g *GIL) NewRawFunc(name string, fn RawFunc) (uintptr, error)

Native callable over raw pointers, the PyMethodDef is shared per name and self carries the handle

func (*GIL) NewRef

func (g *GIL) NewRef(o uintptr) *Ref

Takes a new reference to o for Go to hold

func (*GIL) None

func (g *GIL) None() uintptr

New reference to None

func (*GIL) Own

func (g *GIL) Own(o uintptr) *Ref

Takes ownership of a new reference so Go releases it when the Ref is collected

func (*GIL) RaiseFrom

func (g *GIL) RaiseFrom(exc uintptr, cause error) error

Error raising the exception object exc chained to cause, as raise exc from cause inside its except block does

func (*GIL) Raising

func (g *GIL) Raising(exc *Ref) error

Python error that re-raises the given exception instance when it reaches Python again

func (*GIL) Repr

func (g *GIL) Repr(o uintptr) (string, error)

Text of repr(o)

func (*GIL) SetAttr

func (g *GIL) SetAttr(o uintptr, name string, value any) error

Sets an attribute from a Go value

func (*GIL) Str

func (g *GIL) Str(o uintptr) (string, error)

Text of str(o)

func (*GIL) SysModules

func (g *GIL) SysModules() uintptr

Borrowed sys.modules

func (*GIL) ToPython

func (g *GIL) ToPython(v any) (uintptr, error)

Converts a Go value into a new Python reference

func (*GIL) Truthy

func (g *GIL) Truthy(o uintptr) (bool, error)

Truth value of an object

func (*GIL) TupleItem

func (g *GIL) TupleItem(t uintptr, i int) uintptr

Borrowed item i of a tuple

func (*GIL) Unblocked

func (g *GIL) Unblocked(fn func())

Releases the GIL around blocking Go work, a thread finishing after finalization began never re-enters Python

type Host

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

Host owns the one embedded interpreter of the process

func Start

func Start(opts Options) (*Host, error)

Loads libpython, initializes it and leaves the calling goroutine locked to the OS thread that must call Finalize

func (*Host) Do

func (h *Host) Do(fn func(g *GIL) error) error

Runs fn with the GIL held on a locked OS thread, refusing new work once shutdown began

func (*Host) Finalize

func (h *Host) Finalize(timeout time.Duration) (int, error)

Stops the loop, waits for in flight calls and finalizes, run on the goroutine that called Start

func (*Host) Interpreter

func (h *Host) Interpreter() *Interpreter

Interpreter the host was started from

type Interpreter

type Interpreter struct {
	GOOS         string
	Executable   string
	Prefix       string
	BasePrefix   string
	Major, Minor int
	ABIFlags     string
	Library      string
	IncludeDir   string
	StdlibDir    string
	SitePackages string
	Venv         bool
	Macros       map[string]bool
	Sysconfig    map[string]string
}

Interpreter is a CPython installation resolved from an executable path without running it

func Discover

func Discover(exe string) (*Interpreter, error)

Resolves the interpreter of exe for the running platform

func DiscoverFor

func DiscoverFor(exe, goos string) (*Interpreter, error)

Resolves the interpreter of exe for goos, which lets foreign layouts be checked on this machine

func (*Interpreter) Version

func (in *Interpreter) Version() string

Version string major.minor

type Kind

type Kind int

Kind classifies an object by the builtin type flags of its class, subclasses included

const (
	KindOther Kind = iota
	KindNone
	KindBool
	KindInt
	KindFloat
	KindStr
	KindBytes
	KindByteArray
	KindDict
	KindList
	KindTuple
)

type NamedFunc

type NamedFunc struct {
	Name string
	Fn   Func
}

NamedFunc gives a Func its Python __name__

type NoSharedLibraryError

type NoSharedLibraryError struct {
	Executable string
	LDLibrary  string
	Version    string
	Tried      []string
}

NoSharedLibraryError names an interpreter linked without libpython and the uv commands that supply one

func (*NoSharedLibraryError) Error

func (e *NoSharedLibraryError) Error() string

type Object

type Object interface {
	TypeName() (module, name string)
	GetAttr(g *GIL, name string) (value any, ok bool, err error)
}

Object is a Go value exposed to Python, attribute lookup reaches GetAttr

type Options

type Options struct {
	Interpreter   *Interpreter
	PycachePrefix string
	ExtraPaths    []string
	Environment   bool
	Argv          []string
}

Options select the interpreter and the environment the embedded runtime starts with

type Property

type Property func(g *GIL, self uintptr) (any, error)

Property is a read only attribute computed by Go from the borrowed instance pointer

type PyError

type PyError struct {
	Type      string
	Message   string
	Traceback string
	// contains filtered or unexported fields
}

PyError is a Python exception carried into Go with its type, message and formatted traceback

func (*PyError) Error

func (e *PyError) Error() string

func (*PyError) Exception

func (e *PyError) Exception() *Ref

Exception instance the error carries, nil for an error raised from Go

func (*PyError) Matches

func (e *PyError) Matches(g *GIL, names ...string) bool

Whether the carried exception is an instance of any named builtin or module.Class exception class

func (*PyError) Name

func (e *PyError) Name() string

Short type name, the qualified name without its module

type RawFunc

type RawFunc func(g *GIL, args, kwargs uintptr) (uintptr, error)

RawFunc receives the argument tuple and keyword dict as borrowed pointers and returns a new reference

type Ref

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

Ref is an owned reference held by Go, usable from any goroutine and released under the GIL

func (*Ref) Await

func (r *Ref) Await(ctx context.Context) (any, error)

Runs the referenced awaitable on the loop thread and waits without holding the GIL, a plain value converts

func (*Ref) AwaitIn

func (r *Ref) AwaitIn(ctx context.Context, pyctx *Ref) (*Ref, error)

Runs the referenced awaitable as a task created inside the contextvars context pyctx and returns its raw result

func (*Ref) Call

func (r *Ref) Call(args []any, kwargs map[string]any) (any, error)

Calls the referenced callable from any goroutine and converts the result to Go

func (*Ref) CallAsync

func (r *Ref) CallAsync(ctx context.Context, args []any, kwargs map[string]any) (any, error)

Calls an async callable, runs the awaitable on the loop thread and waits without holding the GIL

func (*Ref) CallLocked

func (r *Ref) CallLocked(g *GIL, args []any, kwargs map[string]any) (any, error)

Calls the referenced callable on the current thread while the GIL is already held

func (*Ref) CallMethod

func (r *Ref) CallMethod(name string, args []any, kwargs map[string]any) (any, error)

Calls a method of the referenced object from any goroutine

func (*Ref) GetAttr

func (r *Ref) GetAttr(name string) (any, error)

Reads an attribute of the referenced object from any goroutine

func (*Ref) GetAttrLocked

func (r *Ref) GetAttrLocked(g *GIL, name string) (any, error)

Reads an attribute while the caller already holds the GIL

func (*Ref) Ptr

func (r *Ref) Ptr() uintptr

Borrowed pointer of the referenced object, valid while the Ref is held

func (*Ref) Release

func (r *Ref) Release()

Drops Go's reference at the next GIL entry

func (*Ref) TypeName

func (r *Ref) TypeName() string

Type name of the referenced object

Jump to

Keyboard shortcuts

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