cpythonutil

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 23 Imported by: ? 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 (
	// Returned for work asked of a host once shutdown has begun
	ErrClosed = errors.New("embedded Python host is shut down")
	// Start called after an interpreter was started in this process, running or finalized, since the process-wide object caches belong to that one
	ErrStarted = errors.New("an embedded Python interpreter was already started in this process")
	// Async work asked of a host whose asyncio loop thread is not running
	ErrNoLoop = errors.New("the host asyncio loop is not running")
	// Finalize called on a thread other than the one Start locked
	ErrWrongThread = errors.New("finalize must run on the goroutine that called Start")
	// A Go value with no Python form or a Python object with no Go form
	ErrUnconvertible = errors.New("value has no conversion")
	// Work that needs other OS threads asked of a child created by os.fork
	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")
	// Start on a platform where purego cannot call libpython or take callbacks from it, matched by errors.ErrUnsupported too
	ErrUnsupported = fmt.Errorf("no embedded CPython support for %s/%s: %w", runtime.GOOS, runtime.GOARCH, errors.ErrUnsupported)
)

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

Existing object pointer passed as an argument, the callee taking its own reference

type Error

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

Python exception carried into Go with its qualified class name and message, the exception instance kept for re-raising and matching

func (*Error) Error

func (e *Error) Error() string

Class and message the way the last line of a Python traceback shows them, the class alone for an empty message

func (*Error) Exception

func (e *Error) Exception() *Ref

The exception instance the error carries, nil for an error made in Go

func (*Error) Matches

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

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

func (*Error) Name

func (e *Error) Name() string

Short class name, the qualified name without its module

func (*Error) Traceback

func (e *Error) Traceback() string

Text traceback.format_exception gives for the exception, formatted under the GIL on first use, empty for an error without an instance

type Exception

type Exception struct {
	Type    string
	Message string
}

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

func (*Exception) Error

func (e *Exception) Error() string

Class and message, the class alone for an empty message

type Func

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

Go function callable from Python with its arguments converted to Go values

type GIL

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

Proof that the goroutine holds an attached thread state of the interpreter, valid inside the call that handed it out and never shared between goroutines

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, a key that is not a str by its str() text

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

func (*GIL) ExceptionMatches

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

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: None, bool, int, float, str, bytes and bytearray to Go values, dicts, lists and tuples by value, 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, any lookup error counting as absent and from 3.13 handed to sys.unraisablehook by CPython

func (*GIL) Host

func (g *GIL) Host() *Host

The 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, ErrNoLoop once the loop thread is gone

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, 0 once Finalize stopped it

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, a new reference

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, a new reference

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, a new reference whose self object carries the Go function

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

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, 0 when i is out of range

func (*GIL) Unblocked

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

Releases the GIL around blocking Go work, even when fn panics; a thread finishing after finalization began parks instead of re-entering Python

type Host

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

The one embedded interpreter of the process

func Start

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

Loads libpython and initializes it once per process, leaving 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(ctx context.Context) (int, error)

Stops the loop, waits for in flight calls and finalizes; runs on the goroutine that called Start, ctx bounding every wait before Py_FinalizeEx

func (*Host) Interpreter

func (h *Host) Interpreter() *Interpreter

The interpreter the host was started from

type InitError

type InitError struct {
	Op       string
	Func     string
	Message  string
	Exit     bool
	ExitCode int
}

Failed step of interpreter initialization with the C function and message CPython reported, or the exit it asked for

func (*InitError) Error

func (e *InitError) Error() string

The step and why it failed

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
}

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

The major.minor text of the interpreter's version

type Kind

type Kind int

Builtin class an object belongs to, subclasses included, the way conversion to Go reads it

const (
	// Any class outside the builtin scalars and containers
	KindOther Kind = iota
	// The None singleton
	KindNone
	// True or False
	KindBool
	// int and its subclasses other than bool
	KindInt
	// float and its subclasses
	KindFloat
	// str and its subclasses
	KindStr
	// bytes and its subclasses
	KindBytes
	// bytearray and its subclasses
	KindByteArray
	// dict and its subclasses
	KindDict
	// list and its subclasses
	KindList
	// tuple and its subclasses
	KindTuple
)

type NamedFunc

type NamedFunc struct {
	Name string
	Fn   Func
}

Func with the __name__ Python shows for it

type NoSharedLibraryError

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

Interpreter linked without libpython, naming the uv commands that supply a shared build

func (*NoSharedLibraryError) Error

func (e *NoSharedLibraryError) Error() string

The interpreter, why it has no usable libpython and how to get one

type Object

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

Go value exposed to Python, its attribute lookups answered by GetAttr

type Options

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

Interpreter and environment the embedded runtime starts with

type Property

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

Read only attribute computed by Go from the borrowed instance pointer

type RawFunc

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

Go function over the borrowed argument tuple and keyword dict, 0 for no keywords, that returns a new reference

type Ref

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

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 converting as it is

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 until it finishes or ctx ends

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, 0 for a nil Ref

func (*Ref) Release

func (r *Ref) Release()

Drops Go's reference at the next GIL entry, once however often it is called, nothing for a nil Ref

func (*Ref) TypeName

func (r *Ref) TypeName() string

Qualified class name of the referenced object, empty once the host is shut down

type SymbolError

type SymbolError struct {
	Name string
	Err  error
}

C API function or data symbol the loaded libpython does not export

func (*SymbolError) Error

func (e *SymbolError) Error() string

The missing symbol and the loader's reason when it gave one

func (*SymbolError) Unwrap

func (e *SymbolError) Unwrap() error

Loader failure behind the missing symbol

Jump to

Keyboard shortcuts

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