py

package module
v3.12.0-alpha.0 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2023 License: BSD-3-Clause Imports: 12 Imported by: 0

README

Go Reference Go Report Card

goPy

What is this?

Idiomatic Python bindings for Google Go

What does that mean?

Instead of simply duplicating the Python C API in Go, this is an attempt to provide the Python API in a form that fits with writing normal Go code.

This means that PyFoo_XXX(foo, ...) is foo.XXX(...), and PyFoo_Check(obj) is foo, ok := obj.(*Foo) to give a couple of examples.

What versions of Python are supported?

This codebase only supports a single version of Python at a time, currently this is version 3.11 (note that this only applies to Major.Minor, not the patch version). For a different version of Python a different branch is needed.

Installation and Building

This module can be installed as normal using go get:

go get gopython.xyz/py/v3

However, you will need Python and libffi libraries installed (along with their dependencies) to build. To build extensions, Python will need to be built with shared libraries.

Python Extensions

Building extensions is supported using the c-shared buildmode. Some boilerplate code is needed to meet the Python C API - this can be generated using the gen_extension command in this repository.

Documentation

Overview

Package py (gopython.xyz/py/v3) provides access to the CPython C API. This package presents an idiomatic Go interface to the CPython C API described at http://docs.python.org/3/c-api/index.html

Instead of simply exposing the C API as-is, this package uses interfaces, embedding, type assertions and methods to try and present the functionality of the Python API in a manner that feels more natural in Go.

Embedding Python

Embedding Python is fully supported, with the ability to initialise the interpreter, enable threading support, manipulate the GIL and call Python API functions to manipulate Python objects.

In addition to providing the ability to use the API to call into Python, calling from Python back into Go is also supported. New types can be implemented in Go and exposed into Python.

In addition to the normal Python C API, an optional (i.e. it must be explicitly enabled) "go" package can be presented to the embedded Python. This gives access to some Go functionality - currently the only extra available is the Chan class, which allows Go and Python code to communicate by exchanging Python objects over a Go channel.

Python Extensions

Building extensions is supported using the c-shared buildmode. Some boilerplate code is needed to meet the Python C API - this can be generated using the gen_extension command in this repository.

Index

Examples

Constants

View Source
const (
	ClassHaveGC   = ClassFlags(C.Py_TPFLAGS_HAVE_GC)
	ClassBaseType = ClassFlags(C.Py_TPFLAGS_BASETYPE)
	ClassHeapType = ClassFlags(C.Py_TPFLAGS_HEAPTYPE)
)

Flags to enable optional features of classes (types).

View Source
const (
	LT = Op(C.Py_LT)
	LE = Op(C.Py_LE)
	EQ = Op(C.Py_EQ)
	NE = Op(C.Py_NE)
	GT = Op(C.Py_GT)
	GE = Op(C.Py_GE)
)

Python comparison operators

Variables

View Source
var (
	BaseException             = newException(C.PyExc_BaseException)
	Exception                 = newException(C.PyExc_Exception)
	BaseExceptionGroup        = newException(C.PyExc_BaseExceptionGroup)
	StopAsyncIteration        = newException(C.PyExc_StopAsyncIteration)
	StopIteration             = newException(C.PyExc_StopIteration)
	GeneratorExit             = newException(C.PyExc_GeneratorExit)
	ArithmeticError           = newException(C.PyExc_ArithmeticError)
	LookupError               = newException(C.PyExc_LookupError)
	AssertionError            = newException(C.PyExc_AssertionError)
	AttributeError            = newException(C.PyExc_AttributeError)
	BufferError               = newException(C.PyExc_BufferError)
	EOFError                  = newException(C.PyExc_EOFError)
	FloatingPointError        = newException(C.PyExc_FloatingPointError)
	OSError                   = newException(C.PyExc_OSError)
	ImportError               = newException(C.PyExc_ImportError)
	ModuleNotFoundError       = newException(C.PyExc_ModuleNotFoundError)
	IndexError                = newException(C.PyExc_IndexError)
	KeyError                  = newException(C.PyExc_KeyError)
	KeyboardInterrupt         = newException(C.PyExc_KeyboardInterrupt)
	MemoryError               = newException(C.PyExc_MemoryError)
	NameError                 = newException(C.PyExc_NameError)
	OverflowError             = newException(C.PyExc_OverflowError)
	RuntimeError              = newException(C.PyExc_RuntimeError)
	RecursionError            = newException(C.PyExc_RecursionError)
	NotImplementedError       = newException(C.PyExc_NotImplementedError)
	SyntaxError               = newException(C.PyExc_SyntaxError)
	IndentationError          = newException(C.PyExc_IndentationError)
	TabError                  = newException(C.PyExc_TabError)
	ReferenceError            = newException(C.PyExc_ReferenceError)
	SystemError               = newException(C.PyExc_SystemError)
	SystemExit                = newException(C.PyExc_SystemExit)
	TypeError                 = newException(C.PyExc_TypeError)
	UnboundLocalError         = newException(C.PyExc_UnboundLocalError)
	UnicodeError              = newException(C.PyExc_UnicodeError)
	UnicodeEncodeError        = newException(C.PyExc_UnicodeEncodeError)
	UnicodeDecodeError        = newException(C.PyExc_UnicodeDecodeError)
	UnicodeTranslateError     = newException(C.PyExc_UnicodeTranslateError)
	ValueError                = newException(C.PyExc_ValueError)
	ZeroDivisionError         = newException(C.PyExc_ZeroDivisionError)
	BlockingIOError           = newException(C.PyExc_BlockingIOError)
	BrokenPipeError           = newException(C.PyExc_BrokenPipeError)
	ChildProcessError         = newException(C.PyExc_ChildProcessError)
	ConnectionError           = newException(C.PyExc_ConnectionError)
	ConnectionAbortedError    = newException(C.PyExc_ConnectionAbortedError)
	ConnectionRefusedError    = newException(C.PyExc_ConnectionRefusedError)
	ConnectionResetError      = newException(C.PyExc_ConnectionResetError)
	FileExistsError           = newException(C.PyExc_FileExistsError)
	FileNotFoundError         = newException(C.PyExc_FileNotFoundError)
	InterruptedError          = newException(C.PyExc_InterruptedError)
	IsADirectoryError         = newException(C.PyExc_IsADirectoryError)
	NotADirectoryError        = newException(C.PyExc_NotADirectoryError)
	PermissionError           = newException(C.PyExc_PermissionError)
	ProcessLookupError        = newException(C.PyExc_ProcessLookupError)
	TimeoutError              = newException(C.PyExc_TimeoutError)
	EnvironmentError          = newException(C.PyExc_EnvironmentError)
	IOError                   = newException(C.PyExc_IOError)
	Warning                   = newException(C.PyExc_Warning)
	UserWarning               = newException(C.PyExc_UserWarning)
	DeprecationWarning        = newException(C.PyExc_DeprecationWarning)
	PendingDeprecationWarning = newException(C.PyExc_PendingDeprecationWarning)
	SyntaxWarning             = newException(C.PyExc_SyntaxWarning)
	RuntimeWarning            = newException(C.PyExc_RuntimeWarning)
	FutureWarning             = newException(C.PyExc_FutureWarning)
	ImportWarning             = newException(C.PyExc_ImportWarning)
	UnicodeWarning            = newException(C.PyExc_UnicodeWarning)
	BytesWarning              = newException(C.PyExc_BytesWarning)
	EncodingWarning           = newException(C.PyExc_EncodingWarning)
	ResourceWarning           = newException(C.PyExc_ResourceWarning)
)
View Source
var BaseType = newType(&C.PyBaseObject_Type)

BaseType is the Type object that represents the BaseObject type.

View Source
var BoolType = newType(&C.PyBool_Type)

BoolType is the Type object that represents the Bool type.

View Source
var ByteArrayType = newType(&C.PyByteArray_Type)

ByteArrayType is the Type object that represents the ByteArray type.

View Source
var BytesType = newType(&C.PyBytes_Type)

BytesType is the Type object that represents the Bytes type.

View Source
var CFunctionType = newType(&C.PyCFunction_Type)

CFunctionType is the Type object that represents the CFunction type.

View Source
var CMethodType = newType(&C.PyCMethod_Type)

CMethodType is the Type object that represents the CMethod type.

View Source
var CellType = newType(&C.PyCell_Type)

CellType is the Type object that represents the Cell type.

View Source
var CodeType = newType(&C.PyCode_Type)

CodeType is the Type object that represents the Code type.

View Source
var ComplexType = newType(&C.PyComplex_Type)

ComplexType is the Type object that represents the Complex type.

View Source
var DictKeysType = newType(&C.PyDictKeys_Type)

DictKeysType is the Type object that represents the DictKeys type.

View Source
var DictType = newType(&C.PyDict_Type)

DictType is the Type object that represents the Dict type.

View Source
var False = (*Bool)(C.pyFalse())

False is the false value of the Bool type. It is a singleton value, all false values refer to the same instance.

View Source
var FloatType = newType(&C.PyFloat_Type)

FloatType is the Type object that represents the Float type.

View Source
var FrameType = newType(&C.PyFrame_Type)

FrameType is the Type object that represents the Frame type.

View Source
var FrozenSetType = newType(&C.PyFrozenSet_Type)

FrozenSetType is the Type object that represents the FrozenSet type.

View Source
var FunctionType = newType(&C.PyFunction_Type)

FunctionType is the Type object that represents the Function type.

View Source
var GenType = newType(&C.PyGen_Type)

GenType is the Type object that represents the Gen type.

View Source
var InstanceMethodType = newType(&C.PyInstanceMethod_Type)

InstanceMethodType is the Type object that represents the InstanceMethod type.

View Source
var ListType = newType(&C.PyList_Type)

ListType is the Type object that represents the List type.

View Source
var LongType = newType(&C.PyLong_Type)

LongType is the Type object that represents the Long type.

View Source
var MemoryViewType = newType(&C.PyMemoryView_Type)

MemoryViewType is the Type object that represents the MemoryView type.

View Source
var MethodType = newType(&C.PyMethod_Type)

MethodType is the Type object that represents the Method type.

View Source
var ModuleType = newType(&C.PyModule_Type)

ModuleType is the Type object that represents the Module type.

View Source
var None = newNoneObject(&C._Py_NoneStruct)

None is the Python equivalent to nil.

View Source
var NotImplemented = newObject(&C._Py_NotImplementedStruct)

NotImplemented is a special Object value than can be returned in some circumstances to indicate that a type method is not implemented.

View Source
var ODictType = newType(&C.PyODict_Type)

ODictType is the Type object that represents the ODict type.

View Source
var SetType = newType(&C.PySet_Type)

SetType is the Type object that represents the Set type.

View Source
var SliceType = newType(&C.PySlice_Type)

SliceType is the Type object that represents the Slice type.

View Source
var SuperType = newType(&C.PySuper_Type)

SuperType is the Type object that represents the Super type.

View Source
var True = (*Bool)(C.pyTrue())

True is the true value of the Bool type. It is a singleton value, all true values refer to the same instance.

View Source
var TupleType = newType(&C.PyTuple_Type)

TupleType is the Type object that represents the Tuple type.

View Source
var TypeType = newType(&C.PyType_Type)

TypeType is the Type object that represents the Type type.

View Source
var UnicodeType = newType(&C.PyUnicode_Type)

UnicodeType is the Type object that represents the Unicode type.

Functions

func AddToPath

func AddToPath(dir string) error

AddToPath appends the given directory to sys.path

func Clear

func Clear[T Object](f *T)

Clear clear the given Object field correctly. This is equivalent to Py_CLEAR from the Python C API.

To clear a field called foo in a struct called self:

py.Clear(&self.foo)

This will set self.foo to nil, and decrement the reference count of foo.

func ClearClassObject

func ClearClassObject(co ClassObject)

ClearClassObject clears any contained Objects in the given instance. This function will correctly clear (i.e. decref and set to nil) any exported contained Objects in the supplied ClassObject. If the ClassObject contains private Objects then they will need to Cleared explicitly using Clear from a Dealloc method.

func Decref

func Decref(obj Object)

Decref decrements obj's reference count, obj may be nil.

func EnterRecursiveCall

func EnterRecursiveCall(where string) bool

EnterRecursiveCall marks a point where a recursive Go-level call is about to be performed. It returns true if the recursive call is permitted, otherwise a Python exception is set and false is returned. where is a string that will be appended to the RuntimeError set if the recursion limit has been exceeded (e.g. " in instance check"). This function needs to be called if the recursive function may not invoke Python code (which automatically tracks recursion depth).

func Finalize

func Finalize()

Finalize shuts down the Python runtime.

You probably want to call the Lock.Finalize method though, as it will ensure that goroutines and threads are managed correctly.

func Incref

func Incref(obj Object)

Incref increments obj's reference count, obj may be nil.

func Initialize

func Initialize()

Initialize initialises the Python runtime.

You probably want InitAndLockWithSignals though, as it doesn't require the caller to worry about goroutines or threads.

func InitializeEx

func InitializeEx(initsigs bool)

InitializeEx initialises the Python runtime.

If initsigs is true then the Python runtime will install signal handlers.

You probably want InitAndLock or InitAndLockWithSignals though, as they doesn't require the caller to worry about goroutines or threads.

func LeaveRecursiveCall

func LeaveRecursiveCall()

LeaveRecursiveCall must be called after a recursive call that was indicated by EnterRecursiveCall.

func Main

func Main(args []string) int

Main is the main Python interpreter entrypoint.

Once this function returns, the Python runtime is shutdown.

func ParseTuple

func ParseTuple(args *Tuple, format string, values ...interface{}) error

func ParseTupleAndKeywords

func ParseTupleAndKeywords(args *Tuple, kw *Dict, format string, kwlist []string, values ...interface{}) error

func PrependToPath

func PrependToPath(dir string) error

PrependToPath prepends the given directory to sys.path

func RefCount

func RefCount(obj Object) int

RefCount returns a copy of the reference count of the Object. This is intended to help with debugging reference count issues, and should not normally be needed.

func RichCompareNativeBool

func RichCompareNativeBool[T constraints.Ordered](a, b T, op Op) (bool, error)

RichCompareNativeBool is a helper function for implementing RichCompareBool. Given two comparable Go values it will compare them with the requested Op and return true or false. If the op is unknown, then a ValueError will be returned.

func SetInterrupt

func SetInterrupt()

func UnblockThreads

func UnblockThreads() func()

UnblockThreads will release the GIL to allow other threads to run. It it intended only for uses where using a Lock to ensure the GIL is held is not needed. The return value is a niladic function to call to regain the GIL.

No check is made that the GIL is currently held.

An example usage might be:

// Call Python code ...

blockThreads := py.UnblockThreads()

// Slow or blocking Go operation

blockThreads()

// Call Python code ...

Types

type A

type A []any

Convenience types for using things like CallGo

type AsPython

type AsPython interface {
	AsPython() (Object, error)
}

AsPython is an optional interface that types can implement to support automatic conversion to Python using the Value methods.

The AsPython function should return a new reference to the Python equivalent of the value.

type AsyncIterator

type AsyncIterator interface {
	Object
	AsAsyncIterator() *AsyncIteratorMethods
}

type AsyncIteratorMethods

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

AsyncIteratorMethods represents an arbitrary async Python iterator.

func AsAsyncIterator

func AsAsyncIterator(obj Object) *AsyncIteratorMethods

func (*AsyncIteratorMethods) Base

func (a *AsyncIteratorMethods) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*AsyncIteratorMethods) Decref

func (a *AsyncIteratorMethods) Decref()

Decref decrements a's reference count, a may not be nil.

func (*AsyncIteratorMethods) Incref

func (a *AsyncIteratorMethods) Incref()

Incref increments a's reference count, a may not be nil.

func (*AsyncIteratorMethods) Type

func (a *AsyncIteratorMethods) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type BaseObject

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

BaseObject is the concrete representation of the Python "Object *". It is used less than in the C API, as the Object interface is mostly used when the type is not fixed. Any Object "o" can be turned into a *BaseObject using the Base() method (i.e. o.Base() returns a *BaseObject that refers to the same underlying Python object as "o"). This allows the Python functions that accept any type of object to be defined as methods on *BaseObject.

func InitExtension

func InitExtension(f func() (*Module, error)) *BaseObject

InitExtension is a helper method for writing an extension init function.

Normally this is called by code generated by cmd/gen_extension

func (*BaseObject) Base

func (b *BaseObject) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*BaseObject) Bytes

func (obj *BaseObject) Bytes() (Object, error)

Bytes returns a Bytes representation of "obj". This is equivalent to the Python "bytes(obj)".

Return value: New Reference.

func (*BaseObject) Call

func (obj *BaseObject) Call(args *Tuple, kwds *Dict) (Object, error)

Call calls obj with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "obj(*args, **kwds)" in Python.

Return value: New Reference.

func (*BaseObject) CallFunction

func (obj *BaseObject) CallFunction(format string, args ...interface{}) (Object, error)

func (*BaseObject) CallFunctionObjArgs

func (obj *BaseObject) CallFunctionObjArgs(args ...Object) (Object, error)

func (*BaseObject) CallGo

func (obj *BaseObject) CallGo(args []any, kwds map[string]any) (Object, error)

CallGo calls obj with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "obj(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*BaseObject) CallGoArgs

func (obj *BaseObject) CallGoArgs(args ...any) (Object, error)

CallGoArgs calls obj with the given args. Returns the result of the call, or an Error on failure. This is equivalent to "obj(*args)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*BaseObject) CallMethod

func (obj *BaseObject) CallMethod(name string, format string, args ...interface{}) (Object, error)

func (*BaseObject) CallMethodGo

func (obj *BaseObject) CallMethodGo(name string, args []any, kwds map[string]any) (Object, error)

CallMethodGo calls the method of obj called name with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "obj.name(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*BaseObject) CallMethodGoArgs

func (obj *BaseObject) CallMethodGoArgs(name string, args ...any) (Object, error)

CallMethodGoArgs calls the method of obj called name with the given args. Returns the result of the call, or an Error on failure. This is equivalent to "obj.name(*args)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*BaseObject) CallMethodObjArgs

func (obj *BaseObject) CallMethodObjArgs(name string, args ...Object) (Object, error)

func (*BaseObject) CallObject

func (obj *BaseObject) CallObject(args *Tuple) (Object, error)

CallObject calls obj with the given args. args may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "obj(*args)" in Python.

Return value: New Reference.

func (*BaseObject) CopyData

func (obj *BaseObject) CopyData(src Object) error

CopyData copies the data from src to obj. Unless both obj and src implement the Buffer Protocol this method will return a TypeError. If both obj and src implement the Buffer Protocol, then the copy may still fail with an error.

func (*BaseObject) Decref

func (b *BaseObject) Decref()

Decref decrements b's reference count, b may not be nil.

func (*BaseObject) DelAttr

func (obj *BaseObject) DelAttr(name Object) error

DelAttr deletes the attribute with the name "name" from "obj". This is equivalent to the Python "del obj.name".

func (*BaseObject) DelAttrString

func (obj *BaseObject) DelAttrString(name string) error

DelAttrString deletes the attribute with the name "name" from "obj". This is equivalent to the Python "del obj.name".

func (*BaseObject) DelItem

func (obj *BaseObject) DelItem(key Object) error

DelItem deletes the element from "obj" that corresponds to "key". This is equivalent to the Python "del obj[key]".

func (*BaseObject) Dir

func (obj *BaseObject) Dir() (Object, error)

func (*BaseObject) Free

func (obj *BaseObject) Free()

Free deallocates the storage (in Python) for obj. After calling this method, obj should no longer be used.

func (*BaseObject) GetAttr

func (obj *BaseObject) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "obj" with the name "name". This is equivalent to the Python "obj.name".

Return value: New Reference.

func (*BaseObject) GetAttrString

func (obj *BaseObject) GetAttrString(name string) (Object, error)

GetAttrString returns the attribute of "obj" with the name "name". This is equivalent to the Python "obj.name".

Return value: New Reference.

func (*BaseObject) GetItem

func (obj *BaseObject) GetItem(key Object) (Object, error)

GetItem returns the element of "obj" corresponding to "key". This is equivalent to the Python "obj[key]".

Return value: New Reference.

func (*BaseObject) HasAttr

func (obj *BaseObject) HasAttr(name Object) bool

HasAttr returns true if "obj" has the attribute "name". This is equivalent to the Python "hasattr(obj, name)".

func (*BaseObject) HasAttrString

func (obj *BaseObject) HasAttrString(name string) bool

HasAttrString returns true if "obj" has the attribute "name". This is equivalent to the Python "hasattr(obj, name)".

func (*BaseObject) Incref

func (b *BaseObject) Incref()

Incref increments b's reference count, b may not be nil.

func (*BaseObject) IsInstance

func (obj *BaseObject) IsInstance(cls Object) (bool, error)

IsInstance returns true if "obj" is an instance of "cls", false otherwise. If "cls" is a Type instead of a class, then true will be return if "obj" is of that type. If "cls" is a Tuple then true will be returned if "obj" is an instance of any of the Objects in the tuple. This is equivalent to the Python "isinstance(obj, cls)".

func (*BaseObject) IsSubclass

func (obj *BaseObject) IsSubclass(cls Object) (bool, error)

IsSubclass returns true if "obj" is a Subclass of "cls", false otherwise. If "cls" is a Tuple, then true is returned if "obj" is a Subclass of any member of "cls". This is equivalent to the Python "issubclass(obj, cls)".

func (*BaseObject) IsTrue

func (obj *BaseObject) IsTrue() bool

IsTrue returns true if the value of obj is considered to be True. This is equivalent to "if obj:" in Python.

func (*BaseObject) Length

func (obj *BaseObject) Length() (int64, error)

Length returns the length of the Object. This is equivalent to the Python "len(obj)".

func (*BaseObject) Not

func (obj *BaseObject) Not() bool

Not returns true if the value of obj is considered to be False. This is equivalent to "if not obj:" in Python.

func (*BaseObject) Repr

func (obj *BaseObject) Repr() (*Unicode, error)

Repr returns a String representation of "obj". This is equivalent to the Python "repr(obj)".

Return value: New Reference.

func (*BaseObject) RichCompare

func (obj *BaseObject) RichCompare(obj2 Object, op Op) (Object, error)

RichCompare compares "obj" with "obj2" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "obj op obj2", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*BaseObject) RichCompareBool

func (obj *BaseObject) RichCompareBool(obj2 Object, op Op) (bool, error)

RichCompare compares "obj" with "obj2" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "obj op obj2", where op is the corresponding Python operator for op.

func (*BaseObject) SetAttr

func (obj *BaseObject) SetAttr(name, value Object) error

SetAttr sets the attribute of "obj" with the name "name" to "value". This is equivalent to the Python "obj.name = value".

func (*BaseObject) SetAttrString

func (obj *BaseObject) SetAttrString(name string, value Object) error

SetAttrString sets the attribute of "obj" with the name "name" to "value". This is equivalent to the Python "obj.name = value".

func (*BaseObject) SetItem

func (obj *BaseObject) SetItem(key, value Object) error

SetItem sets the element of "obj" corresponding to "key" to "value". This is equivalent to the Python "obj[key] = value".

func (*BaseObject) Size

func (obj *BaseObject) Size() (int64, error)

Size returns the length of the Object. This is equivalent to the Python "len(obj)".

func (*BaseObject) Str

func (obj *BaseObject) Str() (*Unicode, error)

Str returns a String representation of "obj". This is equivalent to the Python "str(obj)".

Return value: New Reference.

func (*BaseObject) Type

func (b *BaseObject) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Bool

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

Bool is the representation of the Python bool type. There are only two possible values for a Bool, True and False. Every True value refers to the same instance, and every False value refers to the same value.

func AsBool

func AsBool(obj Object) *Bool

AsBool casts the given obj to a Bool (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Bool, then nil is returned.

Return value: Borrowed Reference.

func NewBool

func NewBool(b bool) *Bool

NewBool returns True if b is true, or False if b is false.

Return value: New Reference.

func (*Bool) Base

func (b *Bool) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Bool) Bool

func (b *Bool) Bool() bool

Bool returns the value of "b" as a bool. true for True, false for False. If "b" is neither True nor False then this function will panic.

func (*Bool) Decref

func (b *Bool) Decref()

Decref is a nop, since Bool values are immortal.

func (*Bool) Incref

func (b *Bool) Incref()

Incref is a nop, since Bool values are immortal.

func (*Bool) String

func (b *Bool) String() string

String returns a printable representation of the Bool "b".

func (*Bool) Type

func (b *Bool) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Buffer

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

func GetBuffer

func GetBuffer(obj Object, flags BufferFlags) (*Buffer, error)

func (*Buffer) FillInfo

func (b *Buffer) FillInfo(exporter Object, buf []byte, readonly bool, flags BufferFlags) error

func (*Buffer) FromContinguous

func (b *Buffer) FromContinguous(buf []byte, order BufferOrder) error

func (*Buffer) GetPointer

func (b *Buffer) GetPointer(indicies ...int) (*byte, error)

func (*Buffer) IsContiguous

func (b *Buffer) IsContiguous(order BufferOrder) bool

func (*Buffer) Release

func (b *Buffer) Release()

func (*Buffer) ToContinguous

func (b *Buffer) ToContinguous(buf []byte, order BufferOrder) error

type BufferFlags

type BufferFlags int

type BufferMethods

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

BufferMethods represents an arbitrary Python type that implements the Buffer Protocol.

func AsBufferMethods

func AsBufferMethods(obj Object) *BufferMethods

AsBuffer returns a BufferMethods instance that refers to the same underlying Python object as obj. If obj doesn't implement the "Buffer Protocol", then nil is returned.

This method is more complete than the BufferProtocol interface, as it will also work with unknown or dynamic types that implement the "Buffer Protocol".

func (*BufferMethods) Base

func (b *BufferMethods) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*BufferMethods) Decref

func (b *BufferMethods) Decref()

Decref decrements b's reference count, b may not be nil.

func (*BufferMethods) GetBuffer

func (b *BufferMethods) GetBuffer(flags BufferFlags) (*Buffer, error)

func (*BufferMethods) Incref

func (b *BufferMethods) Incref()

Incref increments b's reference count, b may not be nil.

func (*BufferMethods) Type

func (b *BufferMethods) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type BufferOrder

type BufferOrder byte
const (
	BufferOrderC       BufferOrder = 'C'
	BufferOrderFortran BufferOrder = 'F'
	BufferOrderAny     BufferOrder = 'A'
)

type BufferProtocol

type BufferProtocol interface {
	Object
	AsBufferMethods() *BufferMethods
}

type ByteArray

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

ByteArray represents objects of the ByteArrayType (or PyByteArray_Type in the Python API) type.

This type implements the Mapping protocol.

This type implements the Sequence protocol.

func AsByteArray

func AsByteArray(obj Object) *ByteArray

AsByteArray casts the given obj to a ByteArray (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a ByteArray, then nil is returned.

Return value: Borrowed Reference.

func NewByteArray

func NewByteArray(b []byte) *ByteArray

NewByteArray returns a new ByteArray instance that contains a copy of the supplied []byte.

Return value: New Reference.

func NewByteArrayFromObject

func NewByteArrayFromObject(o Object) (*ByteArray, error)

NewByteArrayFromObject returns a new ByteArray instance created from the supplied Object.

Return value: New Reference.

func (*ByteArray) AsBufferMethods

func (b *ByteArray) AsBufferMethods() *BufferMethods

AsBufferMethods returns a BufferMethods instance that refers to the same underlying Python object as b.

This method also means that ByteArray implements the BufferProtocol interface.

func (*ByteArray) AsMappingMethods

func (b *ByteArray) AsMappingMethods() *MappingMethods

AsMappingMethods returns a MappingMethods instance that refers to the same underlying Python object as b.

This method also means that ByteArray implements the MappingProtocol interface.

func (*ByteArray) AsSequenceMethods

func (b *ByteArray) AsSequenceMethods() *SequenceMethods

AsSequenceMethods returns a SequenceMethods instance that refers to the same underlying Python object as b.

This method also means that ByteArray implements the SequenceProtocol interface.

func (*ByteArray) Base

func (b *ByteArray) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*ByteArray) Bytes

func (b *ByteArray) Bytes() []byte

Bytes returns the contents of the ByteArray object

NOTE: This function returns a reference to the internal buffer of the ByteArray object, so append or other operations that change the length or capacity MUST NOT be used.

func (*ByteArray) Concat

func (b *ByteArray) Concat(obj Object) (Object, error)

func (*ByteArray) Contains

func (b *ByteArray) Contains(obj Object) (bool, error)

func (*ByteArray) Count

func (b *ByteArray) Count(obj Object) (int, error)

func (*ByteArray) Decref

func (b *ByteArray) Decref()

Decref decrements b's reference count, b may not be nil.

func (*ByteArray) DelIndex

func (b *ByteArray) DelIndex(idx int) error

func (*ByteArray) DelItem

func (b *ByteArray) DelItem(key Object) error

func (*ByteArray) DelItemString

func (b *ByteArray) DelItemString(key string) error

func (*ByteArray) DelSlice

func (b *ByteArray) DelSlice(start, end int) error

func (*ByteArray) GetAttr

func (b *ByteArray) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "b" with the name "name". This is equivalent to the Python "b.name".

Return value: New Reference.

func (*ByteArray) GetBuffer

func (b *ByteArray) GetBuffer(flags BufferFlags) (*Buffer, error)

func (*ByteArray) GetIndex

func (b *ByteArray) GetIndex(idx int) (Object, error)

func (*ByteArray) GetItemString

func (b *ByteArray) GetItemString(key string) (Object, error)

func (*ByteArray) GetSlice

func (b *ByteArray) GetSlice(start, end int) (Object, error)

func (*ByteArray) HasAttr

func (b *ByteArray) HasAttr(name Object) bool

HasAttr returns true if "b" has the attribute "name". This is equivalent to the Python "hasattr(b, name)".

func (*ByteArray) HasKey

func (b *ByteArray) HasKey(key Object) bool

func (*ByteArray) HasKeyString

func (b *ByteArray) HasKeyString(key string) bool

func (*ByteArray) InPlaceConcat

func (b *ByteArray) InPlaceConcat(obj Object) (Object, error)

func (*ByteArray) InPlaceRepeat

func (b *ByteArray) InPlaceRepeat(count int) (Object, error)

func (*ByteArray) Incref

func (b *ByteArray) Incref()

Incref increments b's reference count, b may not be nil.

func (*ByteArray) Index

func (b *ByteArray) Index(obj Object) (int, error)

func (*ByteArray) Iter

func (b *ByteArray) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of b.

func (*ByteArray) List

func (b *ByteArray) List() (*List, error)

func (*ByteArray) Remainder

func (b *ByteArray) Remainder(obj Object) (Object, error)

Remainder returns the remainder of dividing b by obj. The equivalent Python is "b % obj".

Return value: New Reference.

func (*ByteArray) Repeat

func (b *ByteArray) Repeat(count int) (Object, error)

func (*ByteArray) Repr

func (b *ByteArray) Repr() (*Unicode, error)

Repr returns a String representation of "b". This is equivalent to the Python "repr(b)".

Return value: New Reference.

func (*ByteArray) Resize

func (b *ByteArray) Resize(s int) error

Resize changes the size of b's internal buffer to the given size.

func (*ByteArray) RichCompare

func (b *ByteArray) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "b" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "b op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*ByteArray) RichCompareBool

func (b *ByteArray) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "b" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "b op obj", where op is the corresponding Python operator for op.

func (*ByteArray) SetIndex

func (b *ByteArray) SetIndex(idx int, obj Object) error

func (*ByteArray) SetItemString

func (b *ByteArray) SetItemString(key string, v Object) error

func (*ByteArray) SetSlice

func (b *ByteArray) SetSlice(start, end int, obj Object) error

func (*ByteArray) Size

func (b *ByteArray) Size() int

Size returns the size of b. The equivalent Python is "len(b)".

func (*ByteArray) Str

func (b *ByteArray) Str() (*Unicode, error)

Str returns a String representation of "b". This is equivalent to the Python "str(b)".

Return value: New Reference.

func (*ByteArray) String

func (b *ByteArray) String() string

String returns a string representation of the ByteArray

func (*ByteArray) Tuple

func (b *ByteArray) Tuple() (*Tuple, error)

func (*ByteArray) Type

func (b *ByteArray) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Bytes

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

Bytes represents objects of the BytesType (or PyBytes_Type in the Python API) type.

This type implements the Mapping protocol.

This type implements the Sequence protocol.

func AsBytes

func AsBytes(obj Object) *Bytes

AsBytes casts the given obj to a Bytes (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Bytes, then nil is returned.

Return value: Borrowed Reference.

func NewBytes

func NewBytes(b []byte) *Bytes

NewBytes returns a new Bytes instance that contains a copy of the supplied []byte.

Return value: New Reference.

func NewBytesFromObject

func NewBytesFromObject(o Object) (*Bytes, error)

NewBytesFromObject returns a new Bytes instance created from the supplied Object.

Return value: New Reference.

func (*Bytes) AsBufferMethods

func (b *Bytes) AsBufferMethods() *BufferMethods

AsBufferMethods returns a BufferMethods instance that refers to the same underlying Python object as b.

This method also means that Bytes implements the BufferProtocol interface.

func (*Bytes) AsMappingMethods

func (b *Bytes) AsMappingMethods() *MappingMethods

AsMappingMethods returns a MappingMethods instance that refers to the same underlying Python object as b.

This method also means that Bytes implements the MappingProtocol interface.

func (*Bytes) AsSequenceMethods

func (b *Bytes) AsSequenceMethods() *SequenceMethods

AsSequenceMethods returns a SequenceMethods instance that refers to the same underlying Python object as b.

This method also means that Bytes implements the SequenceProtocol interface.

func (*Bytes) Base

func (b *Bytes) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Bytes) Bytes

func (b *Bytes) Bytes() []byte

Bytes returns the contents of the Bytes object

NOTE: This function returns a reference to the internal buffer of the Bytes object, and MUST NOT be changed.

func (*Bytes) Concat

func (b *Bytes) Concat(obj Object) (Object, error)

func (*Bytes) Contains

func (b *Bytes) Contains(obj Object) (bool, error)

func (*Bytes) Count

func (b *Bytes) Count(obj Object) (int, error)

func (*Bytes) Decref

func (b *Bytes) Decref()

Decref decrements b's reference count, b may not be nil.

func (*Bytes) GetAttr

func (b *Bytes) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "b" with the name "name". This is equivalent to the Python "b.name".

Return value: New Reference.

func (*Bytes) GetBuffer

func (b *Bytes) GetBuffer(flags BufferFlags) (*Buffer, error)

func (*Bytes) GetIndex

func (b *Bytes) GetIndex(idx int) (Object, error)

func (*Bytes) GetItemString

func (b *Bytes) GetItemString(key string) (Object, error)

func (*Bytes) GetSlice

func (b *Bytes) GetSlice(start, end int) (Object, error)

func (*Bytes) HasAttr

func (b *Bytes) HasAttr(name Object) bool

HasAttr returns true if "b" has the attribute "name". This is equivalent to the Python "hasattr(b, name)".

func (*Bytes) HasKey

func (b *Bytes) HasKey(key Object) bool

func (*Bytes) HasKeyString

func (b *Bytes) HasKeyString(key string) bool

func (*Bytes) Hash

func (b *Bytes) Hash() (int, error)

Hash computes and returns the hash value of b. The equivalent Python is "hash(b)".

func (*Bytes) Incref

func (b *Bytes) Incref()

Incref increments b's reference count, b may not be nil.

func (*Bytes) Index

func (b *Bytes) Index(obj Object) (int, error)

func (*Bytes) Iter

func (b *Bytes) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of b.

func (*Bytes) List

func (b *Bytes) List() (*List, error)

func (*Bytes) Remainder

func (b *Bytes) Remainder(obj Object) (Object, error)

Remainder returns the remainder of dividing b by obj. The equivalent Python is "b % obj".

Return value: New Reference.

func (*Bytes) Repeat

func (b *Bytes) Repeat(count int) (Object, error)

func (*Bytes) Repr

func (b *Bytes) Repr() (*Unicode, error)

Repr returns a String representation of "b". This is equivalent to the Python "repr(b)".

Return value: New Reference.

func (*Bytes) RichCompare

func (b *Bytes) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "b" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "b op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Bytes) RichCompareBool

func (b *Bytes) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "b" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "b op obj", where op is the corresponding Python operator for op.

func (*Bytes) Size

func (b *Bytes) Size() int

Size returns the size of b. The equivalent Python is "len(b)".

func (*Bytes) Str

func (b *Bytes) Str() (*Unicode, error)

Str returns a String representation of "b". This is equivalent to the Python "str(b)".

Return value: New Reference.

func (*Bytes) String

func (b *Bytes) String() string

func (*Bytes) Tuple

func (b *Bytes) Tuple() (*Tuple, error)

func (*Bytes) Type

func (b *Bytes) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type CFunction

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

CFunction represents objects of the CFunctionType (or PyCFunction_Type in the Python API) type.

func AsCFunction

func AsCFunction(obj Object) *CFunction

AsCFunction casts the given obj to a CFunction (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a CFunction, then nil is returned.

Return value: Borrowed Reference.

func NewCFunction

func NewCFunction(name string, fn interface{}, doc string) (*CFunction, error)

NewCFunction creates a CFunction object from the supplied function.

The supplied function can take one of several forms, which map to different calling conventions supported by Python:

func() (py.Object, error)
func(py.Object) (py.Object, error)
func(*py.Tuple) (py.Object, error)
func(*py.Tuple, *py.Dict) (py.Object, error)

These map to the following PYTHON calling conventions:

  • METH_NOARGS: A function with no arguments
  • METH_O: A function with a single argument, passed directly
  • METH_VARARGS: A function with positional arguments only, passed as a Tuple
  • METH_VARARGS | METH_KEYWORDS: A function with positional and keyword arguments, passed as a Tuple and Dict

Return value: New Reference.

func (*CFunction) Base

func (cf *CFunction) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*CFunction) Call

func (cf *CFunction) Call(args *Tuple, kwds *Dict) (Object, error)

Call calls cf with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "cf(*args, **kwds)" in Python.

Return value: New Reference.

func (*CFunction) CallGo

func (cf *CFunction) CallGo(args []any, kwds map[string]any) (Object, error)

CallGo calls cf with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "cf(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*CFunction) Decref

func (cf *CFunction) Decref()

Decref decrements cf's reference count, cf may not be nil.

func (*CFunction) Flags

func (cf *CFunction) Flags() (int, error)

Flags returns the flags stored in the CFunction. This will include the calling convention to be used.

Return Value: Borrowed Reference.

func (*CFunction) GetAttr

func (cf *CFunction) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "cf" with the name "name". This is equivalent to the Python "cf.name".

Return value: New Reference.

func (*CFunction) HasAttr

func (cf *CFunction) HasAttr(name Object) bool

HasAttr returns true if "cf" has the attribute "name". This is equivalent to the Python "hasattr(cf, name)".

func (*CFunction) Hash

func (cf *CFunction) Hash() (int, error)

Hash computes and returns the hash value of cf. The equivalent Python is "hash(cf)".

func (*CFunction) Incref

func (cf *CFunction) Incref()

Incref increments cf's reference count, cf may not be nil.

func (*CFunction) Repr

func (cf *CFunction) Repr() (*Unicode, error)

Repr returns a String representation of "cf". This is equivalent to the Python "repr(cf)".

Return value: New Reference.

func (*CFunction) RichCompare

func (cf *CFunction) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "cf" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "cf op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*CFunction) RichCompareBool

func (cf *CFunction) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "cf" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "cf op obj", where op is the corresponding Python operator for op.

func (*CFunction) Self

func (cf *CFunction) Self() (Object, error)

Self returns the self Object stored in the CFunction. May return nil, e.g. if the CFunction is a static method.

Return Value: Borrowed Reference.

func (*CFunction) Type

func (cf *CFunction) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type CMethod

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

CMethod represents objects of the CMethodType (or PyCMethod_Type in the Python API) type.

func AsCMethod

func AsCMethod(obj Object) *CMethod

AsCMethod casts the given obj to a CMethod (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a CMethod, then nil is returned.

Return value: Borrowed Reference.

func (*CMethod) Base

func (cm *CMethod) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*CMethod) Decref

func (cm *CMethod) Decref()

Decref decrements cm's reference count, cm may not be nil.

func (*CMethod) Incref

func (cm *CMethod) Incref()

Incref increments cm's reference count, cm may not be nil.

func (*CMethod) Type

func (cm *CMethod) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Callable

type Callable interface {
	Object
	Call(*Tuple, *Dict) (Object, error)
	CallGo([]Object, map[string]Object) (Object, error)
}

type Cell

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

Cell represents objects of the CellType (or PyCell_Type in the Python API) type.

func AsCell

func AsCell(obj Object) *Cell

AsCell casts the given obj to a Cell (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Cell, then nil is returned.

Return value: Borrowed Reference.

func (*Cell) Base

func (ce *Cell) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Cell) Decref

func (ce *Cell) Decref()

Decref decrements ce's reference count, ce may not be nil.

func (*Cell) GetAttr

func (ce *Cell) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "ce" with the name "name". This is equivalent to the Python "ce.name".

Return value: New Reference.

func (*Cell) HasAttr

func (ce *Cell) HasAttr(name Object) bool

HasAttr returns true if "ce" has the attribute "name". This is equivalent to the Python "hasattr(ce, name)".

func (*Cell) Incref

func (ce *Cell) Incref()

Incref increments ce's reference count, ce may not be nil.

func (*Cell) Repr

func (ce *Cell) Repr() (*Unicode, error)

Repr returns a String representation of "ce". This is equivalent to the Python "repr(ce)".

Return value: New Reference.

func (*Cell) RichCompare

func (ce *Cell) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "ce" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "ce op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Cell) RichCompareBool

func (ce *Cell) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "ce" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "ce op obj", where op is the corresponding Python operator for op.

func (*Cell) Type

func (ce *Cell) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Chan

type Chan struct {
	ClassBaseObject
	// contains filtered or unexported fields
}

Chan is a Python object that wraps a Go channel (specifically a "chan Object").

func NewChan

func NewChan(buffer int) (*Chan, error)

NewChan returns a new Chan object, with the channel created using "make(chan Object, buffer)".

Note: This function should only be called if InitGoModule() has been called, as otherwise the Chan Python type has not been initialized. It will always return an error if InitGoModule() has not been called.

Return value: New Reference.

func (*Chan) Chan

func (c *Chan) Chan() chan Object

Chan returns the channel inside the Chan object. This is how Go code can get at the channel to communicate with Python code.

When sending values, a reference count will be "stolen" - i.e. the reference count should be incremented if you want to continue to hold a reference after the send.

When receiving values, you get a new reference - i.e. the reference count should be decremented when you have finished with the value.

func (*Chan) Iter

func (c *Chan) Iter() (Iterator, error)

Iter is called to get an iterator for the item. This is used when running "for ... in c" in Python.

func (*Chan) Next

func (c *Chan) Next() (Object, error)

Next is the iterator API. This function will get called to return the next value.

func (*Chan) Py_close

func (c *Chan) Py_close(args *Tuple, kw *Dict) (ret Object, err error)

Py_close provides a c.close() method when this object is used in Python.

func (*Chan) Py_get

func (c *Chan) Py_get(args *Tuple, kw *Dict) (Object, error)

Py_get provides a c.get() method when this object is used in Python.

func (*Chan) Py_monitor

func (c *Chan) Py_monitor(args *Tuple, kw *Dict) (Object, error)

Py_monitor calls item with items from the channel in a background goroutine. If closed is provided then it will be called when the channel is closed.

func (*Chan) Py_put

func (c *Chan) Py_put(args *Tuple, kw *Dict) (ret Object, err error)

Py_put provides a c.put() method when this object is used in Python.

type Class

type Class struct {
	Name     string
	Flags    ClassFlags
	Doc      string
	BaseType Object
	Object   ClassObject
	Static   map[string]any
	Class    map[string]any
	New      func(*Class, *Tuple, *Dict) (ClassObject, error)
	User     any
	// contains filtered or unexported fields
}

A Class struct instance is used to define a Python class that has been implemented in Go.

Name should be the name of the type in Python, including the package name, e.g. "test.MyClass"

Flags is or'ed with Py_TPFLAGS_DEFAULT and passed through to the tp_flags member

Doc is currently unused.

Once Create has been called, then Class is a valid Object that maps to the Python type instance for this class. Calling RawType will return the same Python instance as a Type.

BaseType is the base type of the class. Although it is an Object, this value must be either a *Type or *Class (or nil for no base type).

Object should be set to a pointer of the struct type that will represent an instance of the Python class. This struct must contain an embedded py.ClassBaseObject. The easiest ways to set Object are either to use a struct literal (i.e. &MyClass{}), or to cast nil (i.e. (*MyClass)(nil)), if the struct is large then the latter method is more efficient (as an instance of the struct is not created).

This struct may have the following special methods (the equivalent Python methods are also indicated):

Init(args *py.Tuple, kwds *py.Dict) error                 // __init__
Call(args *py.Tuple, kwds *py.Dict) (py.Object, error)    // __call__
Repr() (Object, error)                                    // __repr__
Str() (Object, error)                                     // __str__
RichCompare(obj py.Object, op py.Op) (py.Object, error)   // __cmp__

If control over the deallocation process is desired, then the struct can implement:

PyDealloc()

This method will then be called when the instance is being deallocated. If the method is implemented then it takes responsibility for clearing any contained Objects. The py.Clear and py.ClearClassObject functions can be used to assist.

Properties are also supported, by implementing get and set methods:

PyGet_XXX() (py.Object, os.Error)
PySet_XXX(value py.Object) os.Error

Instance methods on the Python class are implemented by methods on the struct type with the Py_ prefix:

Py_ABC(args *py.Tuple) (py.Object, os.Error)
Py_XYX(args *py.Tuple, kwds *py.Dict) (py.Object, os.Error)

NOTE: All of the methods referred to above should use a pointer receiver.

Static defines static methods for the Python class.

Class defines class methods for the Python class. In Go these will be functions that take a *Class as the first argument.

New is an optional constructor for the instance type. The type returned should match that of Object. If New is not provided then a new instance of Object's type will be created.

User is not used by the library code. It can be used to store state for the class methods, etc.

To create a new instance of the Class in Go, then use the Callable methods (i.e. Call or CallGo), which map to the Python expression "cls(...)".

Example
package main

import (
	"fmt"

	"gopython.xyz/py/v3"
)

// myClass is the type that represents the custom class in Go.
type myClass struct {
	py.ClassBaseObject
}

// Call is the method called when the type is called in Python.
//
// This is one of many optional functions that can be implemented on the custom
// class type to respond to actions in Python.
func (m *myClass) Call(args *py.Tuple, kwds *py.Dict) (py.Object, error) {
	var s string
	if err := py.ParseTuple(args, "s", &s); err != nil {
		return nil, err
	}

	fmt.Printf("hello %s", s)

	return py.None, nil
}

// myClassType is a py.Class value that is the Type of myClass.
var myClassType = py.Class{
	Name:   "MyClass",
	Flags:  py.ClassBaseType,
	Doc:    "An example Class",
	Object: (*myClass)(nil),
}

func main() {
	lock := py.InitAndLock()
	defer lock.Finalize()

	// we have to Create the Class before we can use it
	if err := myClassType.Create(); err != nil {
		fmt.Printf("ERROR: %s", err)
		return
	}

	// Python: "m = MyClass()"
	m, err := myClassType.CallGo(nil, nil)
	if err != nil {
		fmt.Printf("ERROR: %s", err)
		return
	}
	defer m.Decref()

	// Python: "m("world")"
	o, err := m.Base().CallGo(py.A{"world"}, nil)
	if err != nil {
		fmt.Printf("ERROR: %s", err)
		return
	}
	defer o.Decref()
}
Output:

hello world

func (*Class) Base

func (cls *Class) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Class) Call

func (cls *Class) Call(args *Tuple, kwds *Dict) (Object, error)

Call calls cls with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "cls(*args, **kwds)" in Python.

The returned value will be a instance of the Class's Object type.

Return value: New Reference.

func (*Class) CallGo

func (cls *Class) CallGo(args []any, kwds map[string]any) (Object, error)

CallGo calls cls with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "cls(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

The returned value will be a instance of the Class's Object type.

Return value: New Reference.

func (*Class) Create

func (cls *Class) Create() (err error)

Create completes the initialisation of the Class by creating the Python type. The created type is then stored in the Class and accessible via the RawType method. A Class is not a valid Python object until Create has been successfully called.

func (*Class) Decref

func (cls *Class) Decref()

Decref decrements cls's reference count, cls may not be nil. This should only be used when the ClassHeapType flag is set.

func (*Class) Incref

func (cls *Class) Incref()

Incref increments cls's reference count, cls may not be nil. This should only be used when the ClassHeapType flag is set.

func (*Class) Instance

func (cls *Class) Instance(o Object) ClassObject

Instance returns o as an instance of the Class, i.e. as the same type as Class.Object. If o is not an instance of Class, an instance of a supertype of Class, or an instance of a subtype of Class which was previously down-casted from Class (or a superclass), then nil will be returned.

Return value: Borrowed Reference.

func (*Class) RawType

func (cls *Class) RawType() *Type

RawType returns the Type that represents this class in Python. The returned value is the same Python object, but as *Type instead of *Class.

Return value: Borrowed Reference.

func (*Class) Super

func (cls *Class) Super(obj Object) (*Super, error)

Super returns a Super object for the Class. If obj is not nil, then it will be a bound Super to that object.

This is equivalent to `super(cls, obj)` in Python, or `super(cls)` if obj is nil.

Return value: New Reference.

func (*Class) Type

func (cls *Class) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python. This will always be TypeType.

type ClassBaseObject

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

ClassBaseObject should be embedded into structs that want to implement ClassObject to be the instance type of a Class.

func (*ClassBaseObject) Base

func (c *ClassBaseObject) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*ClassBaseObject) Class

func (c *ClassBaseObject) Class() *Class

Class returns the *Class for this object.

func (*ClassBaseObject) Decref

func (c *ClassBaseObject) Decref()

Decref decrements c's reference count, c may not be nil.

func (*ClassBaseObject) Incref

func (c *ClassBaseObject) Incref()

Incref increments c's reference count, c may not be nil.

func (*ClassBaseObject) Super

func (c *ClassBaseObject) Super() (*Super, error)

Super returns a Super object for the instance.

This is equivalent to `super(type(c), c)` in Python.

Return value: New Reference.

func (*ClassBaseObject) Type

func (c *ClassBaseObject) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type ClassFlags

type ClassFlags uint32

Class flags. A subset of Python type flags that are supported for types implemented in Go. These flags enable optional features, such as supporting sub-types.

type ClassIteratorProtocol

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

func (*ClassIteratorProtocol) AsIteratorMethods

func (c *ClassIteratorProtocol) AsIteratorMethods() *IteratorMethods

type ClassMappingProtocol

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

func (*ClassMappingProtocol) AsMappingMethods

func (c *ClassMappingProtocol) AsMappingMethods() *MappingMethods

type ClassNumberProtocol

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

func (*ClassNumberProtocol) AsNumberMethods

func (c *ClassNumberProtocol) AsNumberMethods() *NumberMethods

type ClassObject

type ClassObject interface {
	Object
	// contains filtered or unexported methods
}

ClassObject is the interface that has to be implemented by types that are the Go instance type of a Class.

This interface should be implemented by embedding a ClassBaseObject in a struct.

type ClassSequenceProtocol

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

func (*ClassSequenceProtocol) AsSequenceMethods

func (c *ClassSequenceProtocol) AsSequenceMethods() *SequenceMethods

type Code

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

Code represents objects of the CodeType (or PyCode_Type in the Python API) type.

func AsCode

func AsCode(obj Object) *Code

AsCode casts the given obj to a Code (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Code, then nil is returned.

Return value: Borrowed Reference.

func CompileFile

func CompileFile(name string) (*Code, error)

CompileFile compiles the Python file at the given path.

The returned Code can be turned into a Module using ExecCodeModule.

Return value: New Reference.

func (*Code) Base

func (co *Code) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Code) Decref

func (co *Code) Decref()

Decref decrements co's reference count, co may not be nil.

func (*Code) Eval

func (co *Code) Eval(globals, locals Object) (Object, error)

Eval is a simplified function for evaluating a Code object. The code is executed in the environment of the given globals and locals.

Return value: New Reference.

func (*Code) GetAttr

func (co *Code) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "co" with the name "name". This is equivalent to the Python "co.name".

Return value: New Reference.

func (*Code) HasAttr

func (co *Code) HasAttr(name Object) bool

HasAttr returns true if "co" has the attribute "name". This is equivalent to the Python "hasattr(co, name)".

func (*Code) Hash

func (co *Code) Hash() (int, error)

Hash computes and returns the hash value of co. The equivalent Python is "hash(co)".

func (*Code) Incref

func (co *Code) Incref()

Incref increments co's reference count, co may not be nil.

func (*Code) Repr

func (co *Code) Repr() (*Unicode, error)

Repr returns a String representation of "co". This is equivalent to the Python "repr(co)".

Return value: New Reference.

func (*Code) RichCompare

func (co *Code) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "co" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "co op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Code) RichCompareBool

func (co *Code) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "co" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "co op obj", where op is the corresponding Python operator for op.

func (*Code) Type

func (co *Code) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Comparable

type Comparable interface {
	Object
	RichCompare(Object, Op) (Object, error)
}

type Complex

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

Complex represents objects of the ComplexType (or PyComplex_Type in the Python API) type.

This type implements the Number protocol.

func AsComplex

func AsComplex(obj Object) *Complex

AsComplex casts the given obj to a Complex (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Complex, then nil is returned.

Return value: Borrowed Reference.

func NewComplex

func NewComplex[T ~complex64 | ~complex128](v T) (*Complex, error)

func (*Complex) Absolute

func (co *Complex) Absolute() (Object, error)

Absolute returns the absolute value of co. The equivalent Python is "abs(co)".

Return value: New Reference.

func (*Complex) Add

func (co *Complex) Add(obj Object) (Object, error)

Add returns the result of adding co and obj. The equivalent Python is "co + obj".

Return value: New Reference.

func (*Complex) AsNumberMethods

func (co *Complex) AsNumberMethods() *NumberMethods

AsNumberMethods returns a NumberMethods instance that refers to the same underlying Python object as co.

This method also means that Complex implements the NumberProtocol interface.

func (*Complex) Base

func (co *Complex) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Complex) Complex128

func (co *Complex) Complex128() complex128

func (*Complex) Decref

func (co *Complex) Decref()

Decref decrements co's reference count, co may not be nil.

func (*Complex) GetAttr

func (co *Complex) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "co" with the name "name". This is equivalent to the Python "co.name".

Return value: New Reference.

func (*Complex) HasAttr

func (co *Complex) HasAttr(name Object) bool

HasAttr returns true if "co" has the attribute "name". This is equivalent to the Python "hasattr(co, name)".

func (*Complex) Hash

func (co *Complex) Hash() (int, error)

Hash computes and returns the hash value of co. The equivalent Python is "hash(co)".

func (*Complex) Incref

func (co *Complex) Incref()

Incref increments co's reference count, co may not be nil.

func (*Complex) Multiply

func (co *Complex) Multiply(obj Object) (Object, error)

Multiply returns the result of multiplying co by obj. The equivalent Python is "co * obj".

Return value: New Reference.

func (*Complex) Negative

func (co *Complex) Negative() (Object, error)

Negative returns the negation of co. The equivalent Python is "-co".

Return value: New Reference.

func (*Complex) Positive

func (co *Complex) Positive() (Object, error)

Positive returns the positive of co. The equivalent Python is "+co".

Return value: New Reference.

func (*Complex) Power

func (co *Complex) Power(obj1, obj2 Object) (Object, error)

Power returns the result of the Python "pow(co, obj1, obj2)", where obj2 is optional.

Return value: New Reference.

func (*Complex) Repr

func (co *Complex) Repr() (*Unicode, error)

Repr returns a String representation of "co". This is equivalent to the Python "repr(co)".

Return value: New Reference.

func (*Complex) RichCompare

func (co *Complex) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "co" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "co op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Complex) RichCompareBool

func (co *Complex) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "co" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "co op obj", where op is the corresponding Python operator for op.

func (*Complex) String

func (co *Complex) String() string

func (*Complex) Subtract

func (co *Complex) Subtract(obj Object) (Object, error)

Subtract returns the result of subtracting obj from co. The equivalent Python is "co - obj".

Return value: New Reference.

func (*Complex) TrueDivide

func (co *Complex) TrueDivide(obj Object) (Object, error)

TrueDivide returns the approximate result of dividing co by obj. The result is approximate due to the limited representational accuracy of binary floating point numbers. The equivalent Python is "co / obj".

Return value: New Reference.

func (*Complex) Type

func (co *Complex) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Dict

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

Dict represents objects of the DictType (or PyDict_Type in the Python API) type.

This type implements the Mapping protocol.

func AsDict

func AsDict(obj Object) *Dict

AsDict casts the given obj to a Dict (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Dict, then nil is returned.

Return value: Borrowed Reference.

func NewDict

func NewDict() (*Dict, error)

NewDict creates a new empty dictionary.

Return value: New Reference.

func NewDictFromMap

func NewDictFromMap(m map[Object]Object) (*Dict, error)

NewDictFromMap creates a new dictionary containing the values from the given map.

Return value: New Reference.

func NewDictFromMapString

func NewDictFromMapString(m map[string]Object) (*Dict, error)

NewDictFromMapString creates a new dictionary containing the values from the given map.

Return value: New Reference.

func NewDictFromValues

func NewDictFromValues(m map[any]any) (*Dict, error)

NewDictFromValues creates a new dictionary containing the values from the given map.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func NewDictFromValuesGeneric

func NewDictFromValuesGeneric[K comparable, V any](m map[K]V) (*Dict, error)

NewDictFromValuesGeneric creates a new dictionary containing the values from the given map. This is very similar to NewDictFromValues except that the provided map can use specific types rather than having to be map[any]any.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func NewDictFromValuesString

func NewDictFromValuesString[V any](m map[string]V) (*Dict, error)

NewDictFromValuesString creates a new dictionary containing the values from the given map.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func NewDictProxy

func NewDictProxy(obj Object) (*Dict, error)

func (*Dict) AsMappingMethods

func (d *Dict) AsMappingMethods() *MappingMethods

AsMappingMethods returns a MappingMethods instance that refers to the same underlying Python object as d.

This method also means that Dict implements the MappingProtocol interface.

func (*Dict) Base

func (d *Dict) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Dict) CheckExact

func (d *Dict) CheckExact() bool

CheckExact returns true if d is an actual dictionary object, and not an instance of a sub type.

func (*Dict) Clear

func (d *Dict) Clear()

Clear empties the dictionary d of all key-value pairs.

func (*Dict) Contains

func (d *Dict) Contains(obj Object) (bool, error)

func (*Dict) Copy

func (d *Dict) Copy() (Object, error)

Copy returns a new dictionary that contains the same key-values pairs as d.

Return value: New Reference.

func (*Dict) Decref

func (d *Dict) Decref()

Decref decrements d's reference count, d may not be nil.

func (*Dict) DelItem

func (d *Dict) DelItem(key Object) error

func (*Dict) DelItemString

func (d *Dict) DelItemString(key string) error

func (*Dict) GetAttr

func (d *Dict) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "d" with the name "name". This is equivalent to the Python "d.name".

Return value: New Reference.

func (*Dict) GetItem

func (d *Dict) GetItem(key Object) (Object, error)

GetItem returns the Object from dictionary d which has the key "key". If there is no such Object, then nil is returned (without an error).

Return value: Borrowed Reference.

func (*Dict) GetItemString

func (d *Dict) GetItemString(key string) (Object, error)

func (*Dict) HasAttr

func (d *Dict) HasAttr(name Object) bool

HasAttr returns true if "d" has the attribute "name". This is equivalent to the Python "hasattr(d, name)".

func (*Dict) HasKey

func (d *Dict) HasKey(key Object) bool

func (*Dict) HasKeyString

func (d *Dict) HasKeyString(key string) bool

func (*Dict) Hash

func (d *Dict) Hash() (int, error)

Hash computes and returns the hash value of d. The equivalent Python is "hash(d)".

func (*Dict) InPlaceOr

func (d *Dict) InPlaceOr(obj Object) (Object, error)

InPlaceOr returns the bitwise or of d and obj. This is done in place. The equivalent Python is "d |= obj".

Return value: New Reference.

func (*Dict) Incref

func (d *Dict) Incref()

Incref increments d's reference count, d may not be nil.

func (*Dict) Items

func (d *Dict) Items() (*List, error)

Items returns a *List containing all the items from the dictionary d, as with the Python "d.items()".

Return value: New Reference.

func (*Dict) Iter

func (d *Dict) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of d.

func (*Dict) Keys

func (d *Dict) Keys() (*List, error)

Keys returns a *List containing all the keys from the dictionary d, as with the Python "d.keys()".

Return value: New Reference.

func (*Dict) Map

func (d *Dict) Map() map[Object]Object

Map returns a Go map that contains the values from the Python dictionary, indexed by the keys. The keys and values are the same as in the Python dictionary, but changes to the Go map are not propogated back to the Python dictionary.

Note: the map holds borrowed references

func (*Dict) MapString

func (d *Dict) MapString() (map[string]Object, error)

MapString is similar to Map, except that the keys are first converted to strings. If the keys are not all Python strings, then an error is returned.

Note: the map holds borrowed references

func (*Dict) Merge

func (d *Dict) Merge(o Object, override bool) error

Merge merges key values pairs from Object o (which may be a dictionary, or an object that supports "o.keys()" and "o[key]") into the dictionary d. If override is true then a matching key in d will have it's value replaced by the one in o, else the value in d will be left.

func (*Dict) MergeFromSeq2

func (d *Dict) MergeFromSeq2(o Object, override bool) error

MergeFromSeq2 merges key values pairs from the Object o (which must be an iterable object, where each item is an iterable of length 2 - the key value pairs). If override is true then the last key value pair with the same key wins, otherwise the first instance does (where an instance already in d counts before any in o).

func (*Dict) Or

func (d *Dict) Or(obj Object) (Object, error)

Or returns the bitwise or of d and obj. The equivalent Python is "d | obj".

Return value: New Reference.

func (*Dict) Repr

func (d *Dict) Repr() (*Unicode, error)

Repr returns a String representation of "d". This is equivalent to the Python "repr(d)".

Return value: New Reference.

func (*Dict) RichCompare

func (d *Dict) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "d" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "d op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Dict) RichCompareBool

func (d *Dict) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "d" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "d op obj", where op is the corresponding Python operator for op.

func (*Dict) SetItem

func (d *Dict) SetItem(key, val Object) error

SetItem inserts "val" into dictionary d with the key "key". If "key" is not hashable, then a TypeError will be returned.

func (*Dict) SetItemString

func (d *Dict) SetItemString(key string, v Object) error

func (*Dict) Size

func (d *Dict) Size() int

Size returns the size of d. The equivalent Python is "len(d)".

func (*Dict) String

func (d *Dict) String() string

String returns a string representation of the contents of the dictionary d.

func (*Dict) Type

func (d *Dict) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

func (*Dict) Update

func (d *Dict) Update(o Object) error

Update replaces key values pairs in d with those from o. It is equivalent to d.Merge(o, true) in Go, or "d.update(o)" in Python.

func (*Dict) Values

func (d *Dict) Values() (*List, error)

Values returns a *List containing all the values from the dictionary d, as with the Python "d.values()".

Return value: New Reference.

type DictKeys

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

DictKeys represents objects of the DictKeysType (or PyDictKeys_Type in the Python API) type.

func AsDictKeys

func AsDictKeys(obj Object) *DictKeys

AsDictKeys casts the given obj to a DictKeys (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a DictKeys, then nil is returned.

Return value: Borrowed Reference.

func (*DictKeys) And

func (d *DictKeys) And(obj Object) (Object, error)

And returns the bitwise and of d and obj. The equivalent Python is "d & obj".

Return value: New Reference.

func (*DictKeys) Base

func (d *DictKeys) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*DictKeys) Contains

func (d *DictKeys) Contains(obj Object) (bool, error)

func (*DictKeys) Decref

func (d *DictKeys) Decref()

Decref decrements d's reference count, d may not be nil.

func (*DictKeys) GetAttr

func (d *DictKeys) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "d" with the name "name". This is equivalent to the Python "d.name".

Return value: New Reference.

func (*DictKeys) HasAttr

func (d *DictKeys) HasAttr(name Object) bool

HasAttr returns true if "d" has the attribute "name". This is equivalent to the Python "hasattr(d, name)".

func (*DictKeys) Incref

func (d *DictKeys) Incref()

Incref increments d's reference count, d may not be nil.

func (*DictKeys) Iter

func (d *DictKeys) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of d.

func (*DictKeys) Or

func (d *DictKeys) Or(obj Object) (Object, error)

Or returns the bitwise or of d and obj. The equivalent Python is "d | obj".

Return value: New Reference.

func (*DictKeys) Repr

func (d *DictKeys) Repr() (*Unicode, error)

Repr returns a String representation of "d". This is equivalent to the Python "repr(d)".

Return value: New Reference.

func (*DictKeys) RichCompare

func (d *DictKeys) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "d" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "d op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*DictKeys) RichCompareBool

func (d *DictKeys) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "d" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "d op obj", where op is the corresponding Python operator for op.

func (*DictKeys) Size

func (d *DictKeys) Size() int

Size returns the size of d. The equivalent Python is "len(d)".

func (*DictKeys) Subtract

func (d *DictKeys) Subtract(obj Object) (Object, error)

Subtract returns the result of subtracting obj from d. The equivalent Python is "d - obj".

Return value: New Reference.

func (*DictKeys) Type

func (d *DictKeys) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

func (*DictKeys) Xor

func (d *DictKeys) Xor(obj Object) (Object, error)

Xor returns the bitwise xor of d and obj. The equivalent Python is "d ^ obj".

Return value: New Reference.

type Error

type Error struct {
	Kind  Object
	Value Object
	// contains filtered or unexported fields
}

Error represents a Python exception as a Go struct that implements the error interface. It allows Go code to handle Python exceptions in an idiomatic Go fashion.

func NewError

func NewError(kind Object, format string, args ...interface{}) *Error

NewError returns a new Error of the specified kind, and with the value being a new Unicode containing the string created the given format and args.

func NewErrorV

func NewErrorV(kind Object, value Object) *Error

NewErrorV returns a new Error of the specified kind, and with the given value.

func (*Error) Error

func (e *Error) Error() string

Error() returns a string representation of the Python exception represented by the Error e. This is the same as the final line of the Python output from an uncaught exception.

func (*Error) Matches

func (e *Error) Matches(exc Object) bool

Matches returns true if e.Kind matches the exception in exc. If exc is a Class, then true is returned if e.Kind is an instance. If exc is a Tuple, then all elements (and recursively for sub elements) are searched for a match.

func (*Error) Normalize

func (e *Error) Normalize()

Normalize adjusts e.Kind/e.Value in the case that the values aren't normalized to start with. It's possible that an Error returned from Python might have e.Kind be a Class, with e.Value not being an instance of that class, Normalize will fix this. The separate normalization is implemented in Python to improve performance.

type ExceptionClass

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

ExceptionClass is the representation of the Python exception type. All exceptions are instances of this type.

The Err and ErrV methods can be used to generate an error of a particular exception type.

var ChanClosedError *ExceptionClass

ChanClosedError is an exception raised by the Chan type when the channel has been closed. This variable is initialised as part of initialising the Go module, so it should not be used if the Go module is not initialised.

func AsExceptionClass

func AsExceptionClass(err error) *ExceptionClass

AsException returns the ExceptionClass if the error is a py.Error (uses errors.As) with an ExceptionClass as the Kind, or nil otherwise.

Return value: Borrowed reference.

func NewException

func NewException(name string, base, dict Object) (*ExceptionClass, error)

NewException creates and returns a new exception class. The name argument must be the name of the new exception, of the form "module.classname". The base and dict arguments are normally nil. This creates a class object derived from Exception.

The __module__ attribute of the new class is set to the first part (up to the last dot) of the name argument, and the class name is set to the last part (after the last dot). The base argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes. The dict argument can be used to specify a dictionary of class variables and methods.

Return value: New Reference.

func NewExceptionWithDoc

func NewExceptionWithDoc(name, doc string, base, dict Object) (*ExceptionClass, error)

NewExceptionWithDoc creates and returns a new exception class. This is the same as NewException, except that docstring can also be supplied. If non-empty it will be used as the docstring for the exception class.

Return value: New Reference.

func (*ExceptionClass) Base

func (e *ExceptionClass) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*ExceptionClass) Decref

func (e *ExceptionClass) Decref()

Decref decrements e's reference count, e may not be nil.

func (*ExceptionClass) Err

func (e *ExceptionClass) Err(format string, args ...interface{}) *Error

Err returns a new Error of the specified kind (e), and with the value being a new String containing the string created with the given format and args.

func (*ExceptionClass) ErrV

func (e *ExceptionClass) ErrV(obj Object) *Error

ErrV returns a new Error of the specified kind (e), and with the given value.

func (*ExceptionClass) Incref

func (e *ExceptionClass) Incref()

Incref increments e's reference count, e may not be nil.

func (*ExceptionClass) Type

func (e *ExceptionClass) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Float

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

Float represents objects of the FloatType (or PyFloat_Type in the Python API) type.

This type implements the Number protocol.

func AsFloat

func AsFloat(obj Object) *Float

AsFloat casts the given obj to a Float (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Float, then nil is returned.

Return value: Borrowed Reference.

func NewFloat

func NewFloat[T ~float32 | ~float64](f T) (*Float, error)

func NewFloatString

func NewFloatString(v string) (*Float, error)

func (*Float) Absolute

func (f *Float) Absolute() (Object, error)

Absolute returns the absolute value of f. The equivalent Python is "abs(f)".

Return value: New Reference.

func (*Float) Add

func (f *Float) Add(obj Object) (Object, error)

Add returns the result of adding f and obj. The equivalent Python is "f + obj".

Return value: New Reference.

func (*Float) AsNumberMethods

func (f *Float) AsNumberMethods() *NumberMethods

AsNumberMethods returns a NumberMethods instance that refers to the same underlying Python object as f.

This method also means that Float implements the NumberProtocol interface.

func (*Float) Base

func (f *Float) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Float) Decref

func (f *Float) Decref()

Decref decrements f's reference count, f may not be nil.

func (*Float) Divmod

func (f *Float) Divmod(obj Object) (Object, error)

Divmod returns the result of the Python "divmod(f, obj)".

Return value: New Reference.

func (*Float) Float64

func (f *Float) Float64() float64

func (*Float) FloorDivide

func (f *Float) FloorDivide(obj Object) (Object, error)

FloorDivide returns the floor of dividing f by obj. The equivalent Python is "f // obj".

Return value: New Reference.

func (*Float) GetAttr

func (f *Float) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "f" with the name "name". This is equivalent to the Python "f.name".

Return value: New Reference.

func (*Float) HasAttr

func (f *Float) HasAttr(name Object) bool

HasAttr returns true if "f" has the attribute "name". This is equivalent to the Python "hasattr(f, name)".

func (*Float) Hash

func (f *Float) Hash() (int, error)

Hash computes and returns the hash value of f. The equivalent Python is "hash(f)".

func (*Float) Incref

func (f *Float) Incref()

Incref increments f's reference count, f may not be nil.

func (*Float) Long

func (f *Float) Long() (*Long, error)

func (*Float) Multiply

func (f *Float) Multiply(obj Object) (Object, error)

Multiply returns the result of multiplying f by obj. The equivalent Python is "f * obj".

Return value: New Reference.

func (*Float) Negative

func (f *Float) Negative() (Object, error)

Negative returns the negation of f. The equivalent Python is "-f".

Return value: New Reference.

func (*Float) Positive

func (f *Float) Positive() (Object, error)

Positive returns the positive of f. The equivalent Python is "+f".

Return value: New Reference.

func (*Float) Power

func (f *Float) Power(obj1, obj2 Object) (Object, error)

Power returns the result of the Python "pow(f, obj1, obj2)", where obj2 is optional.

Return value: New Reference.

func (*Float) Remainder

func (f *Float) Remainder(obj Object) (Object, error)

Remainder returns the remainder of dividing f by obj. The equivalent Python is "f % obj".

Return value: New Reference.

func (*Float) Repr

func (f *Float) Repr() (*Unicode, error)

Repr returns a String representation of "f". This is equivalent to the Python "repr(f)".

Return value: New Reference.

func (*Float) RichCompare

func (f *Float) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "f" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "f op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Float) RichCompareBool

func (f *Float) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "f" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "f op obj", where op is the corresponding Python operator for op.

func (*Float) String

func (f *Float) String() string

func (*Float) Subtract

func (f *Float) Subtract(obj Object) (Object, error)

Subtract returns the result of subtracting obj from f. The equivalent Python is "f - obj".

Return value: New Reference.

func (*Float) TrueDivide

func (f *Float) TrueDivide(obj Object) (Object, error)

TrueDivide returns the approximate result of dividing f by obj. The result is approximate due to the limited representational accuracy of binary floating point numbers. The equivalent Python is "f / obj".

Return value: New Reference.

func (*Float) Type

func (f *Float) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Frame

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

Frame represents objects of the FrameType (or PyFrame_Type in the Python API) type.

func AsFrame

func AsFrame(obj Object) *Frame

AsFrame casts the given obj to a Frame (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Frame, then nil is returned.

Return value: Borrowed Reference.

func GetFrame

func GetFrame() (*Frame, error)

func (*Frame) Base

func (f *Frame) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Frame) Decref

func (f *Frame) Decref()

Decref decrements f's reference count, f may not be nil.

func (*Frame) DelAttr

func (f *Frame) DelAttr(name, value Object) error

DelAttr deletes the attribute with the name "name" from "f". This is equivalent to the Python "del f.name".

func (*Frame) GetAttr

func (f *Frame) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "f" with the name "name". This is equivalent to the Python "f.name".

Return value: New Reference.

func (*Frame) GetLineNumber

func (f *Frame) GetLineNumber() int

func (*Frame) HasAttr

func (f *Frame) HasAttr(name Object) bool

HasAttr returns true if "f" has the attribute "name". This is equivalent to the Python "hasattr(f, name)".

func (*Frame) Incref

func (f *Frame) Incref()

Incref increments f's reference count, f may not be nil.

func (*Frame) Repr

func (f *Frame) Repr() (*Unicode, error)

Repr returns a String representation of "f". This is equivalent to the Python "repr(f)".

Return value: New Reference.

func (*Frame) SetAttr

func (f *Frame) SetAttr(name, value Object) error

SetAttr sets the attribute of "f" with the name "name" to "value". This is equivalent to the Python "f.name = value".

func (*Frame) Type

func (f *Frame) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type FrozenSet

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

FrozenSet represents objects of the FrozenSetType (or PyFrozenSet_Type in the Python API) type.

func AsFrozenSet

func AsFrozenSet(obj Object) *FrozenSet

AsFrozenSet casts the given obj to a FrozenSet (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a FrozenSet, then nil is returned.

Return value: Borrowed Reference.

func NewFrozenSet

func NewFrozenSet(o Object) (*FrozenSet, error)

NewFrozenSet create a new Python frozenset instance. The set contains the values from the passed Object if it is iterable (a TypeError is returned if "o" is not iterable). An empty set is returned if o is nil.

Return value: New Reference.

func (*FrozenSet) Base

func (f *FrozenSet) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*FrozenSet) CheckExact

func (f *FrozenSet) CheckExact() bool

func (*FrozenSet) Contains

func (f *FrozenSet) Contains(obj Object) (bool, error)

func (*FrozenSet) Decref

func (f *FrozenSet) Decref()

Decref decrements f's reference count, f may not be nil.

func (*FrozenSet) GetAttr

func (f *FrozenSet) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "s" with the name "name". This is equivalent to the Python "s.name".

Return value: New Reference.

func (*FrozenSet) HasAttr

func (f *FrozenSet) HasAttr(name Object) bool

HasAttr returns true if "s" has the attribute "name". This is equivalent to the Python "hasattr(s, name)".

func (*FrozenSet) Hash

func (f *FrozenSet) Hash() (int, error)

Hash computes and returns the hash value of s. The equivalent Python is "hash(s)".

func (*FrozenSet) Incref

func (f *FrozenSet) Incref()

Incref increments f's reference count, f may not be nil.

func (*FrozenSet) Iter

func (f *FrozenSet) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of f.

func (*FrozenSet) Repr

func (f *FrozenSet) Repr() (*Unicode, error)

Repr returns a String representation of "s". This is equivalent to the Python "repr(s)".

Return value: New Reference.

func (*FrozenSet) RichCompare

func (f *FrozenSet) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "f" with "obj" using the specified operation (LE, GE etc.), and returns the result (True or False). The equivalent Python is "f op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*FrozenSet) RichCompareBool

func (f *FrozenSet) RichCompareBool(obj Object, op Op) (bool, error)

RichCompareBool compares "f" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "f op obj", where op is the corresponding Python operator for op.

func (*FrozenSet) Size

func (f *FrozenSet) Size() int

func (*FrozenSet) Type

func (f *FrozenSet) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Function

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

Function represents objects of the FunctionType (or PyFunction_Type in the Python API) type.

func AsFunction

func AsFunction(obj Object) *Function

AsFunction casts the given obj to a Function (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Function, then nil is returned.

Return value: Borrowed Reference.

func NewFunction

func NewFunction(code Object, globals Object) (*Function, error)

NewFunction returns a new Function object that is associated with the given "code" and "globals". "globals" must be a dictionary, and it should hold the global variables for the function.

The function inherits its docstring, name and __module__ from the "code" object, the argument defaults and closure are initialised to nil.

Return value: New Reference.

func (*Function) Base

func (f *Function) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Function) Call

func (f *Function) Call(args *Tuple, kwds *Dict) (Object, error)

Call calls f with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "f(*args, **kwds)" in Python.

Return value: New Reference.

func (*Function) CallGo

func (f *Function) CallGo(args []any, kwds map[string]any) (Object, error)

CallGo calls f with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "f(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*Function) Closure

func (f *Function) Closure() (Object, error)

Closure returns the closure associated with function "f". This may be nil or a Tuple of Cell objects.

Return value: Borrowed Reference.

func (*Function) Code

func (f *Function) Code() (Object, error)

Code returns the code object associated with the function "f".

Return value: Borrowed Reference.

func (*Function) Decref

func (f *Function) Decref()

Decref decrements f's reference count, f may not be nil.

func (*Function) Defaults

func (f *Function) Defaults() (Object, error)

Defaults returns the argument default values for the function "f". This may be nil or a Tuple of values.

Return value: Borrowed Reference.

func (*Function) Globals

func (f *Function) Globals() (Object, error)

Globals returns the globals dictionary associated with the function "f".

Return value: Borrowed Reference.

func (*Function) Incref

func (f *Function) Incref()

Incref increments f's reference count, f may not be nil.

func (*Function) Module

func (f *Function) Module() (Object, error)

Module returns the __module__ attribute of the function "f".

Return value: Borrowed Reference.

func (*Function) Repr

func (f *Function) Repr() (*Unicode, error)

Repr returns a String representation of "f". This is equivalent to the Python "repr(f)".

Return value: New Reference.

func (*Function) SetClosure

func (f *Function) SetClosure(o Object) error

SetClosure sets the closure associated with function "f". "o" must be either a Tuple of Cell objects, or None.

func (*Function) SetDefaults

func (f *Function) SetDefaults(o Object) error

SetDefaults sets the argument default values for the function "f". "o" must be either a Tuple, or None.

func (*Function) Type

func (f *Function) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type GILState

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

GILState holds the GIL state for the current thread.

func GILStateEnsure

func GILStateEnsure() *GILState

GILStateEnsure will ensure that the current thread holds the GIL.

Use of Lock is recommend over direct use of this function, as it will correctly manage the interaction with goroutines.

When the function returns, the current thread will hold the GIL and be able to call arbitrary Python code. Failure is a fatal error.

Note: This function is just a convenience for creating an empty GILState and calling Ensure.

func (*GILState) Ensure

func (g *GILState) Ensure()

GILStateEnsure will ensure that the current thread holds the GIL.

Use of Lock is recommend over direct use of this function, as it will correctly manage the interaction with goroutines.

When the function returns, the current thread will hold the GIL and be able to call arbitrary Python code. Failure is a fatal error.

func (*GILState) Release

func (g *GILState) Release()

Release will release the GIL and restore the previously saved state.

Use of Lock is recommend over direct use of this function, as it will correctly manage the interaction with goroutines.

No Python calls should be until the GIL is obtained again.

type Gen

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

Gen represents objects of the GenType (or PyGen_Type in the Python API) type.

This type implements the Iterator protocol.

func AsGen

func AsGen(obj Object) *Gen

AsGen casts the given obj to a Gen (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Gen, then nil is returned.

Return value: Borrowed Reference.

func (*Gen) AsIteratorMethods

func (g *Gen) AsIteratorMethods() *IteratorMethods

AsIteratorMethods returns a IteratorMethods instance that refers to the same underlying Python object as g.

This method also means that Gen implements the Iterator interface.

func (*Gen) Base

func (g *Gen) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Gen) Decref

func (g *Gen) Decref()

Decref decrements g's reference count, g may not be nil.

func (*Gen) GetAttr

func (g *Gen) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "g" with the name "name". This is equivalent to the Python "g.name".

Return value: New Reference.

func (*Gen) HasAttr

func (g *Gen) HasAttr(name Object) bool

HasAttr returns true if "g" has the attribute "name". This is equivalent to the Python "hasattr(g, name)".

func (*Gen) Incref

func (g *Gen) Incref()

Incref increments g's reference count, g may not be nil.

func (*Gen) Iter

func (g *Gen) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of g.

func (*Gen) Next

func (g *Gen) Next() (Object, error)

Next is the Iterator method, it returns the next item from the Object being iterated. When the end is reached then both the Object and the error will be nil.

func (*Gen) Repr

func (g *Gen) Repr() (*Unicode, error)

Repr returns a String representation of "g". This is equivalent to the Python "repr(g)".

Return value: New Reference.

func (*Gen) Type

func (g *Gen) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type GoMethod

type GoMethod struct {
	Name string
	Func interface{}
	Doc  string
}

GoMethod describes a Go function to be used in Python. Name is the name of the function in Python, Doc is the docstring to be used, and Func is the function to be called.

See NewCFunction for details of the supported function signatures.

type Hashable

type Hashable interface {
	Object
	Hash() (Object, error)
}

type Index

type Index interface {
	Object
	Index() (*Long, error)
}

type InstanceMethod

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

InstanceMethod represents objects of the InstanceMethodType (or PyInstanceMethod_Type in the Python API) type.

func AsInstanceMethod

func AsInstanceMethod(obj Object) *InstanceMethod

AsInstanceMethod casts the given obj to a InstanceMethod (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a InstanceMethod, then nil is returned.

Return value: Borrowed Reference.

func (*InstanceMethod) Base

func (i *InstanceMethod) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*InstanceMethod) Call

func (i *InstanceMethod) Call(args *Tuple, kwds *Dict) (Object, error)

Call calls i with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "i(*args, **kwds)" in Python.

Return value: New Reference.

func (*InstanceMethod) CallGo

func (i *InstanceMethod) CallGo(args []any, kwds map[string]any) (Object, error)

CallGo calls i with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "i(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*InstanceMethod) Decref

func (i *InstanceMethod) Decref()

Decref decrements i's reference count, i may not be nil.

func (*InstanceMethod) DelAttr

func (i *InstanceMethod) DelAttr(name, value Object) error

DelAttr deletes the attribute with the name "name" from "i". This is equivalent to the Python "del i.name".

func (*InstanceMethod) GetAttr

func (i *InstanceMethod) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "i" with the name "name". This is equivalent to the Python "i.name".

Return value: New Reference.

func (*InstanceMethod) HasAttr

func (i *InstanceMethod) HasAttr(name Object) bool

HasAttr returns true if "i" has the attribute "name". This is equivalent to the Python "hasattr(i, name)".

func (*InstanceMethod) Incref

func (i *InstanceMethod) Incref()

Incref increments i's reference count, i may not be nil.

func (*InstanceMethod) Repr

func (i *InstanceMethod) Repr() (*Unicode, error)

Repr returns a String representation of "i". This is equivalent to the Python "repr(i)".

Return value: New Reference.

func (*InstanceMethod) RichCompare

func (i *InstanceMethod) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "i" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "i op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*InstanceMethod) RichCompareBool

func (i *InstanceMethod) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "i" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "i op obj", where op is the corresponding Python operator for op.

func (*InstanceMethod) SetAttr

func (i *InstanceMethod) SetAttr(name, value Object) error

SetAttr sets the attribute of "i" with the name "name" to "value". This is equivalent to the Python "i.name = value".

func (*InstanceMethod) Type

func (i *InstanceMethod) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Iterable

type Iterable interface {
	Object
	Iter() (Iterator, error)
}

func AsIterable

func AsIterable(obj Object) Iterable

AsIterable returns obj as an Iterable. If obj is not an Iterable, then nil will be returned.

type IterableMethods

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

IterableMethods represents an arbitrary Python iterable.

func (*IterableMethods) Base

func (i *IterableMethods) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*IterableMethods) Decref

func (i *IterableMethods) Decref()

Decref decrements i's reference count, i may not be nil.

func (*IterableMethods) Incref

func (i *IterableMethods) Incref()

Incref increments i's reference count, i may not be nil.

func (*IterableMethods) Iter

func (i *IterableMethods) Iter() (Iterator, error)

Iter returns an iterator for the object represented by i.

Return value: New Reference.

func (*IterableMethods) Type

func (i *IterableMethods) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Iterator

type Iterator interface {
	Object
	Next() (Object, error)
}

func AsIterator

func AsIterator(obj Object) Iterator

AsIterator returns obj as an Iterator. If obj is not an Iterator, then nil will be returned.

func GetIterator

func GetIterator(obj Object) (Iterator, error)

GetIterator returns an iterator for the given object. If the object is neither already an iterator nor iterable, then a TypeError is returned.

Return value: New Reference.

type IteratorMethods

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

IteratorMethods represents an arbitrary Python iterator.

func (*IteratorMethods) Base

func (i *IteratorMethods) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*IteratorMethods) Decref

func (i *IteratorMethods) Decref()

Decref decrements i's reference count, i may not be nil.

func (*IteratorMethods) Incref

func (i *IteratorMethods) Incref()

Incref increments i's reference count, i may not be nil.

func (*IteratorMethods) Next

func (i *IteratorMethods) Next() (Object, error)

Next returns the next item from the iterator. When the iterator is exhausted both the returned Object and error will be nil.

Return value: New Reference.

func (*IteratorMethods) Type

func (i *IteratorMethods) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type IteratorProtocol

type IteratorProtocol interface {
	Object
	AsIteratorMethods() *IteratorMethods
}

type K

type K map[string]any

Convenience types for using things like CallGo

type List

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

List represents objects of the ListType (or PyList_Type in the Python API) type.

This type implements the Mapping protocol.

This type implements the Sequence protocol.

func AsList

func AsList(obj Object) *List

AsList casts the given obj to a List (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a List, then nil is returned.

Return value: Borrowed Reference.

func NewList

func NewList(size int) (*List, error)

NewList creates a new Python List instance. The created list has initial length "size".

Note: If size > 0, then the objects in the returned list are initialised to nil. Thus you cannot use Abstract API functions, or expose the object to Python code without first filling in all the created slots with list.SetItem() or list.SetItemSteal().

Return value: New Reference.

func NewListFromObjects

func NewListFromObjects(objects ...Object) (*List, error)

NewListFromObjects create a new Python List from the supplied Objects. The references are stolen.

Return value: New Reference.

func NewListFromSlice

func NewListFromSlice[T any](values []T) (*List, error)

NewListFromSlice creates a new Python List from the supplied slice. The values are converted to Objects using NewValue.

Return value: New Reference.

func NewListFromValues

func NewListFromValues(values ...any) (*List, error)

NewListFromValues creates a new Python List from the supplied values. The values are converted to Objects using NewValue.

Return value: New Reference.

func (*List) Append

func (l *List) Append(obj Object) error

Append adds the Object obj to list l, by appending it to the end of the list. This is equivalent to the Python "l.append(obj)"

func (*List) AsMappingMethods

func (l *List) AsMappingMethods() *MappingMethods

AsMappingMethods returns a MappingMethods instance that refers to the same underlying Python object as l.

This method also means that List implements the MappingProtocol interface.

func (*List) AsSequenceMethods

func (l *List) AsSequenceMethods() *SequenceMethods

AsSequenceMethods returns a SequenceMethods instance that refers to the same underlying Python object as l.

This method also means that List implements the SequenceProtocol interface.

func (*List) Base

func (l *List) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*List) BorrowIndex

func (l *List) BorrowIndex(idx int) (Object, error)

BorrowIndex returns the Object contained in list l at index idx. If idx is out of bounds for l, then an IndexError will be returned.

Return value: Borrowed Reference.

func (*List) CheckExact

func (l *List) CheckExact() bool

CheckExact returns true if if l is an actual Python list, and not a sub type.

func (*List) Concat

func (l *List) Concat(obj Object) (Object, error)

func (*List) Contains

func (l *List) Contains(obj Object) (bool, error)

func (*List) Count

func (l *List) Count(obj Object) (int, error)

func (*List) Decref

func (l *List) Decref()

Decref decrements l's reference count, l may not be nil.

func (*List) DelIndex

func (l *List) DelIndex(idx int) error

func (*List) DelItem

func (l *List) DelItem(key Object) error

func (*List) DelItemString

func (l *List) DelItemString(key string) error

func (*List) DelSlice

func (l *List) DelSlice(start, end int) error

func (*List) GetAttr

func (l *List) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "l" with the name "name". This is equivalent to the Python "l.name".

Return value: New Reference.

func (*List) GetIndex

func (l *List) GetIndex(idx int) (Object, error)

func (*List) GetItemString

func (l *List) GetItemString(key string) (Object, error)

func (*List) GetSlice

func (l *List) GetSlice(start, end int) (Object, error)

func (*List) HasAttr

func (l *List) HasAttr(name Object) bool

HasAttr returns true if "l" has the attribute "name". This is equivalent to the Python "hasattr(l, name)".

func (*List) HasKey

func (l *List) HasKey(key Object) bool

func (*List) HasKeyString

func (l *List) HasKeyString(key string) bool

func (*List) Hash

func (l *List) Hash() (int, error)

Hash computes and returns the hash value of l. The equivalent Python is "hash(l)".

func (*List) InPlaceConcat

func (l *List) InPlaceConcat(obj Object) (Object, error)

func (*List) InPlaceRepeat

func (l *List) InPlaceRepeat(count int) (Object, error)

func (*List) Incref

func (l *List) Incref()

Incref increments l's reference count, l may not be nil.

func (*List) Index

func (l *List) Index(obj Object) (int, error)

func (*List) Insert

func (l *List) Insert(idx int, obj Object) error

Insert adds the Object obj to list l, by inserting it before the value currently stored at index idx (making obj the new value with index idx). This is equivalent to the Python "l.insert(idx, obj)".

func (*List) Iter

func (l *List) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of l.

func (*List) Repeat

func (l *List) Repeat(count int) (Object, error)

func (*List) Repr

func (l *List) Repr() (*Unicode, error)

Repr returns a String representation of "l". This is equivalent to the Python "repr(l)".

Return value: New Reference.

func (*List) Reverse

func (l *List) Reverse() error

Reverse will reverse the values in the List in place. The equivalent Python is "l.reverse()".

func (*List) RichCompare

func (l *List) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "l" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "l op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*List) RichCompareBool

func (l *List) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "l" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "l op obj", where op is the corresponding Python operator for op.

func (*List) SetIndex

func (l *List) SetIndex(idx int, obj Object) error

func (*List) SetIndexSteal

func (l *List) SetIndexSteal(idx int, obj Object) error

SetIndexSteal sets the Object at index idx in list l to Object obj.

Note: This method "steals" a reference to obj, and discards a reference to the current value of idx in l (if there is one).

func (*List) SetItemString

func (l *List) SetItemString(key string, v Object) error

func (*List) SetSlice

func (l *List) SetSlice(start, end int, obj Object) error

func (*List) Size

func (l *List) Size() int

Size returns the size of l. The equivalent Python is "len(l)".

func (*List) Slice

func (l *List) Slice() []Object

Slice returns the list l as a Go Object slice. The order of objects is copied from the Python list, but changes to the slice are not reflected in the Python list.

Note: The returned slice contains borrowed references to the values.

func (*List) Sort

func (l *List) Sort() error

Sort will sort the values in the List in place. The equivalent Python is "l.sort()".

func (*List) String

func (l *List) String() string

String returns a string representation of the list l.

func (*List) Tuple

func (l *List) Tuple() (*Tuple, error)

func (*List) Type

func (l *List) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Lock

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

Lock is a high-level representation of the Python Global Interpreter Lock (GIL) and thread state. When calling from Go into Python the GIL needs to be held and the appropriate thread state loaded. Lock also calls runtime.LockOSThread() to make sure that the calling goroutine doesn't move thread whilst calling Python code which would invalidate the per-thread state.

A single instance of Lock is not intended to be shared, but instead represents a private view of the GIL. If the Lock is locked then you have the GIL and can execute Python code, if the Lock is unlocked (or unblocked) then you don't have the GIL and can't execute Python code.

Basic usage is:

lock = py.NewLock()

// Call Python code ...

lock.Unlock()

If it appropriate to let other Python threads run (e.g. during a long computation, or blocking operation), then there are two options. Either unlock:

lock = py.NewLock()

// Call Python code ...

lock.Unlock()

// Slow or blocking Go operation

lock.Lock()

// Call Python code ...

lock.Unlock()

or unblock threads, which will not call runtime.UnlockOSThread() but it less expensive, as we do not free and then recreate a thread state variable:

lock = py.NewLock()

// Call Python code ...

lock.UnblockThreads()

// Slow or blocking Go operation

lock.BlockThreads()

// Call Python code ...

lock.Unlock()

Note: The Lock and Unlock methods will panic if Python is not initialised, so Lock and Unlock should not be called before Python is initialised, or after Python is finalized.

The simplest way to embed and use Python is using the InitAndLock and Lock.Finalize wrappers:

lock := py.InitAndLock()
defer py.Finalize()

func InitAndLock

func InitAndLock() *Lock

InitAndLock is a convenience function. It initializes Python, enables thread support, and returns a locked Lock instance.

func InitAndLockWithSignals

func InitAndLockWithSignals() *Lock

InitAndLockWithSignals is similar to InitAndLock, except that it initializes the Python signal handling too.

func NewLock

func NewLock() (lock *Lock)

NewLock returns a new locked Lock

func (*Lock) BlockThreads

func (lock *Lock) BlockThreads()

BlockThreads() reclaims the GIL (and restores per-thread state), after it has been released by UnblockThreads().

If this function is called without UnblockThreads() having been called, then nothing happens and the function returns immediately.

If the lock is not locked, this function will panic.

func (*Lock) Finalize

func (lock *Lock) Finalize()

Finalize shuts down the Python runtime.

Finalize also unlocks the Lock, also calling Unlock will cause Python to crash.

If the Lock is not locked, or if this is not the outer-most lock of a nested set then this function will panic.

However, it is not necessary to call BlockThreads() before calling Finalize(), even if UnblockThreads() has been called.

func (*Lock) Lock

func (lock *Lock) Lock()

Lock locks the lock. When it returns everything is setup for calling into Python. No other Python threads will run until either Unlock() or UnblockThreads() are called.

If the lock is already locked when this function is called, then nothing happens, and the function will return immediately.

func (*Lock) UnblockThreads

func (lock *Lock) UnblockThreads()

UnblockThreads() releases the GIL so that other Python threads may run. It does not free the per-thread state created by Lock, nor does it call runtime.UnlockOSThread(). This function is intended to allow other Python threads to run whilst the calling code is either performing a slow/long running operation or is going to block.

Nothing happens if this function is called more than once, all calls but the first will be ignored.

If the lock is not locked, this function will panic.

func (*Lock) Unlock

func (lock *Lock) Unlock()

Unlock unlocks the lock. When it returns no calls into Python may be made.

If the lock is not locked when this function is called, then nothing happens, and the function returns immediately. Also, it is not necessary to call BlockThreads() before calling Unlock(), even if UnblockThreads() has been called.

type Long

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

Long represents objects of the LongType (or PyLong_Type in the Python API) type.

This type implements the Number protocol.

func AsLong

func AsLong(obj Object) *Long

AsLong casts the given obj to a Long (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Long, then nil is returned.

Return value: Borrowed Reference.

func NewLong

func NewLong[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint8 | ~uint16 | ~uint32](i T) *Long

func (*Long) Absolute

func (l *Long) Absolute() (Object, error)

Absolute returns the absolute value of l. The equivalent Python is "abs(l)".

Return value: New Reference.

func (*Long) Add

func (l *Long) Add(obj Object) (Object, error)

Add returns the result of adding l and obj. The equivalent Python is "l + obj".

Return value: New Reference.

func (*Long) And

func (l *Long) And(obj Object) (Object, error)

And returns the bitwise and of l and obj. The equivalent Python is "l & obj".

Return value: New Reference.

func (*Long) AsInt

func (l *Long) AsInt(exc *ExceptionClass) (int, error)

func (*Long) AsNumberMethods

func (l *Long) AsNumberMethods() *NumberMethods

AsNumberMethods returns a NumberMethods instance that refers to the same underlying Python object as l.

This method also means that Long implements the NumberProtocol interface.

func (*Long) Base

func (l *Long) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Long) Decref

func (l *Long) Decref()

Decref decrements l's reference count, l may not be nil.

func (*Long) Divmod

func (l *Long) Divmod(obj Object) (Object, error)

Divmod returns the result of the Python "divmod(l, obj)".

Return value: New Reference.

func (*Long) Float

func (l *Long) Float() (*Float, error)

func (*Long) FloorDivide

func (l *Long) FloorDivide(obj Object) (Object, error)

FloorDivide returns the floor of dividing l by obj. The equivalent Python is "l // obj".

Return value: New Reference.

func (*Long) GetAttr

func (l *Long) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "l" with the name "name". This is equivalent to the Python "l.name".

Return value: New Reference.

func (*Long) HasAttr

func (l *Long) HasAttr(name Object) bool

HasAttr returns true if "l" has the attribute "name". This is equivalent to the Python "hasattr(l, name)".

func (*Long) Hash

func (l *Long) Hash() (int, error)

Hash computes and returns the hash value of l. The equivalent Python is "hash(l)".

func (*Long) Incref

func (l *Long) Incref()

Incref increments l's reference count, l may not be nil.

func (*Long) Index

func (l *Long) Index() (*Long, error)

func (*Long) Int64

func (l *Long) Int64() int64

func (*Long) Invert

func (l *Long) Invert() (Object, error)

Invert returns the bitwise negation of l. The equivalent Python is "-l".

Return value: New Reference.

func (*Long) LShift

func (l *Long) LShift(obj Object) (Object, error)

LShift returns the result of left shifting l by obj. The equivalent Python is "l << obj".

Return value: New Reference.

func (*Long) Multiply

func (l *Long) Multiply(obj Object) (Object, error)

Multiply returns the result of multiplying l by obj. The equivalent Python is "l * obj".

Return value: New Reference.

func (*Long) Negative

func (l *Long) Negative() (Object, error)

Negative returns the negation of l. The equivalent Python is "-l".

Return value: New Reference.

func (*Long) Or

func (l *Long) Or(obj Object) (Object, error)

Or returns the bitwise or of l and obj. The equivalent Python is "l | obj".

Return value: New Reference.

func (*Long) Positive

func (l *Long) Positive() (Object, error)

Positive returns the positive of l. The equivalent Python is "+l".

Return value: New Reference.

func (*Long) Power

func (l *Long) Power(obj1, obj2 Object) (Object, error)

Power returns the result of the Python "pow(l, obj1, obj2)", where obj2 is optional.

Return value: New Reference.

func (*Long) RShift

func (l *Long) RShift(obj Object) (Object, error)

RShift returns the result of right shifting l by obj. The equivalent Python is "l << obj".

Return value: New Reference.

func (*Long) Remainder

func (l *Long) Remainder(obj Object) (Object, error)

Remainder returns the remainder of dividing l by obj. The equivalent Python is "l % obj".

Return value: New Reference.

func (*Long) Repr

func (l *Long) Repr() (*Unicode, error)

Repr returns a String representation of "l". This is equivalent to the Python "repr(l)".

Return value: New Reference.

func (*Long) RichCompare

func (l *Long) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "l" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "l op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Long) RichCompareBool

func (l *Long) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "l" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "l op obj", where op is the corresponding Python operator for op.

func (*Long) String

func (l *Long) String() string

func (*Long) Subtract

func (l *Long) Subtract(obj Object) (Object, error)

Subtract returns the result of subtracting obj from l. The equivalent Python is "l - obj".

Return value: New Reference.

func (*Long) ToBase

func (l *Long) ToBase(base int) (*Long, error)

func (*Long) TrueDivide

func (l *Long) TrueDivide(obj Object) (Object, error)

TrueDivide returns the approximate result of dividing l by obj. The result is approximate due to the limited representational accuracy of binary floating point numbers. The equivalent Python is "l / obj".

Return value: New Reference.

func (*Long) Type

func (l *Long) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

func (*Long) Xor

func (l *Long) Xor(obj Object) (Object, error)

Xor returns the bitwise xor of l and obj. The equivalent Python is "l ^ obj".

Return value: New Reference.

type MappingMethods

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

MappingMethods is a concrete realisation of the full set of Mapping Protocol methods. A type that implements the "Mapping Protocol" can be turned into a MappingMethods instance using AsMapping.

Note that the methods not already implemented on the type itself may return an error, as not all methods are implemented by all types that support the protocol.

func AsMappingMethods

func AsMappingMethods(obj Object) *MappingMethods

AsMapping returns a MappingMethods instance that refers to the same underlying Python object as obj. If obj doesn't implement the "Mapping Protocol", then nil is returned.

This method is more complete than the MappingProtocol interface, as it will also work with unknown or dynamic types that implement the "Mapping Protocol".

func (*MappingMethods) AsMappingMethods

func (m *MappingMethods) AsMappingMethods() *MappingMethods

func (*MappingMethods) Base

func (m *MappingMethods) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*MappingMethods) Decref

func (m *MappingMethods) Decref()

Decref decrements m's reference count, m may not be nil.

func (*MappingMethods) DelItem

func (m *MappingMethods) DelItem(key Object) error

func (*MappingMethods) DelItemString

func (m *MappingMethods) DelItemString(key string) error

func (*MappingMethods) GetItemString

func (m *MappingMethods) GetItemString(key string) (Object, error)

func (*MappingMethods) HasKey

func (m *MappingMethods) HasKey(key Object) bool

func (*MappingMethods) HasKeyString

func (m *MappingMethods) HasKeyString(key string) bool

func (*MappingMethods) Incref

func (m *MappingMethods) Incref()

Incref increments m's reference count, m may not be nil.

func (*MappingMethods) Items

func (m *MappingMethods) Items() (Object, error)

func (*MappingMethods) Keys

func (m *MappingMethods) Keys() (Object, error)

func (*MappingMethods) SetItemString

func (m *MappingMethods) SetItemString(key string, v Object) error

func (*MappingMethods) Size

func (m *MappingMethods) Size() (int, error)

func (*MappingMethods) Type

func (m *MappingMethods) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

func (*MappingMethods) Values

func (m *MappingMethods) Values() (Object, error)

type MappingProtocol

type MappingProtocol interface {
	Object
	AsMappingMethods() *MappingMethods
}

MappingProtocol is an interface that is implemented by types that implement the Python "Mapping Protocol".

type MemoryView

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

MemoryView represents objects of the MemoryViewType (or PyMemoryView_Type in the Python API) type.

This type implements the Mapping protocol.

This type implements the Sequence protocol.

func AsMemoryView

func AsMemoryView(obj Object) *MemoryView

AsMemoryView casts the given obj to a MemoryView (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a MemoryView, then nil is returned.

Return value: Borrowed Reference.

func (*MemoryView) AsBufferMethods

func (m *MemoryView) AsBufferMethods() *BufferMethods

AsBufferMethods returns a BufferMethods instance that refers to the same underlying Python object as m.

This method also means that MemoryView implements the BufferProtocol interface.

func (*MemoryView) AsMappingMethods

func (m *MemoryView) AsMappingMethods() *MappingMethods

AsMappingMethods returns a MappingMethods instance that refers to the same underlying Python object as m.

This method also means that MemoryView implements the MappingProtocol interface.

func (*MemoryView) AsSequenceMethods

func (m *MemoryView) AsSequenceMethods() *SequenceMethods

AsSequenceMethods returns a SequenceMethods instance that refers to the same underlying Python object as m.

This method also means that MemoryView implements the SequenceProtocol interface.

func (*MemoryView) Base

func (m *MemoryView) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*MemoryView) Count

func (m *MemoryView) Count(obj Object) (int, error)

func (*MemoryView) Decref

func (m *MemoryView) Decref()

Decref decrements m's reference count, m may not be nil.

func (*MemoryView) DelItem

func (m *MemoryView) DelItem(key Object) error

func (*MemoryView) DelItemString

func (m *MemoryView) DelItemString(key string) error

func (*MemoryView) DelSlice

func (m *MemoryView) DelSlice(start, end int) error

func (*MemoryView) GetAttr

func (m *MemoryView) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "m" with the name "name". This is equivalent to the Python "m.name".

Return value: New Reference.

func (*MemoryView) GetBuffer

func (m *MemoryView) GetBuffer(flags BufferFlags) (*Buffer, error)

func (*MemoryView) GetIndex

func (m *MemoryView) GetIndex(idx int) (Object, error)

func (*MemoryView) GetItemString

func (m *MemoryView) GetItemString(key string) (Object, error)

func (*MemoryView) GetSlice

func (m *MemoryView) GetSlice(start, end int) (Object, error)

func (*MemoryView) HasAttr

func (m *MemoryView) HasAttr(name Object) bool

HasAttr returns true if "m" has the attribute "name". This is equivalent to the Python "hasattr(m, name)".

func (*MemoryView) HasKey

func (m *MemoryView) HasKey(key Object) bool

func (*MemoryView) HasKeyString

func (m *MemoryView) HasKeyString(key string) bool

func (*MemoryView) Hash

func (m *MemoryView) Hash() (int, error)

Hash computes and returns the hash value of m. The equivalent Python is "hash(m)".

func (*MemoryView) Incref

func (m *MemoryView) Incref()

Incref increments m's reference count, m may not be nil.

func (*MemoryView) Index

func (m *MemoryView) Index(obj Object) (int, error)

func (*MemoryView) Iter

func (m *MemoryView) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of m.

func (*MemoryView) List

func (m *MemoryView) List() (*List, error)

func (*MemoryView) Repr

func (m *MemoryView) Repr() (*Unicode, error)

Repr returns a String representation of "m". This is equivalent to the Python "repr(m)".

Return value: New Reference.

func (*MemoryView) RichCompare

func (m *MemoryView) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "m" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "m op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*MemoryView) RichCompareBool

func (m *MemoryView) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "m" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "m op obj", where op is the corresponding Python operator for op.

func (*MemoryView) SetItemString

func (m *MemoryView) SetItemString(key string, v Object) error

func (*MemoryView) SetSlice

func (m *MemoryView) SetSlice(start, end int, obj Object) error

func (*MemoryView) Size

func (m *MemoryView) Size() int

Size returns the size of m. The equivalent Python is "len(m)".

func (*MemoryView) Tuple

func (m *MemoryView) Tuple() (*Tuple, error)

func (*MemoryView) Type

func (m *MemoryView) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Method

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

Method represents objects of the MethodType (or PyMethod_Type in the Python API) type.

func AsMethod

func AsMethod(obj Object) *Method

AsMethod casts the given obj to a Method (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Method, then nil is returned.

Return value: Borrowed Reference.

func NewMethod

func NewMethod(function, self Object) (*Method, error)

func (*Method) Base

func (m *Method) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Method) Call

func (m *Method) Call(args *Tuple, kwds *Dict) (Object, error)

Call calls m with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "m(*args, **kwds)" in Python.

Return value: New Reference.

func (*Method) CallGo

func (m *Method) CallGo(args []any, kwds map[string]any) (Object, error)

CallGo calls m with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "m(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*Method) Decref

func (m *Method) Decref()

Decref decrements m's reference count, m may not be nil.

func (*Method) DelAttr

func (m *Method) DelAttr(name, value Object) error

DelAttr deletes the attribute with the name "name" from "m". This is equivalent to the Python "del m.name".

func (*Method) GetAttr

func (m *Method) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "m" with the name "name". This is equivalent to the Python "m.name".

Return value: New Reference.

func (*Method) HasAttr

func (m *Method) HasAttr(name Object) bool

HasAttr returns true if "m" has the attribute "name". This is equivalent to the Python "hasattr(m, name)".

func (*Method) Hash

func (m *Method) Hash() (int, error)

Hash computes and returns the hash value of m. The equivalent Python is "hash(m)".

func (*Method) Incref

func (m *Method) Incref()

Incref increments m's reference count, m may not be nil.

func (*Method) Repr

func (m *Method) Repr() (*Unicode, error)

Repr returns a String representation of "m". This is equivalent to the Python "repr(m)".

Return value: New Reference.

func (*Method) RichCompare

func (m *Method) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "m" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "m op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Method) RichCompareBool

func (m *Method) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "m" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "m op obj", where op is the corresponding Python operator for op.

func (*Method) Self

func (m *Method) Self() Object

func (*Method) SetAttr

func (m *Method) SetAttr(name, value Object) error

SetAttr sets the attribute of "m" with the name "name" to "value". This is equivalent to the Python "m.name = value".

func (*Method) Type

func (m *Method) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Module

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

Bool is the representation of the Python module type.

func AsModule

func AsModule(obj Object) *Module

AsModule casts the given obj to a Module (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Module, then nil is returned.

Return value: Borrowed Reference.

func CreateModule

func CreateModule(md *ModuleDef) (*Module, error)

CreateModule builds a Module instance given a ModuleDef.

Return value: New Reference.

func ExecCodeModule

func ExecCodeModule(name string, code *Code) (*Module, error)

ExecCodeModule builds a Python module from the supplied Code.

Return value: New Reference.

func Import

func Import(name string) (*Module, error)

Import tries to import the Python module with the given name. This is equivalent to then "__import__()" function call in Python. In particular it will use the import hooks from the current environment.

Return value: New Reference.

func InitGoModule

func InitGoModule() (*Module, error)

InitGoModule creates and registers (and returns) the special built-in "go" module. This module exports go specific items to Python that can be accessed by calling "import go". Since this function also initialises the Python representations that are exported by the "go" module it must be called before any of these types (e.g. Chan) can be used.

This function may be called more than once to get at the *Module, the module will only be created and registered once.

Note: The return value is a borrowed ref.

func NewModule

func NewModule(name string) (*Module, error)

NewModule creates a new, empty Python module.

Return value: New Reference.

func (*Module) AddIntConstant

func (m *Module) AddIntConstant(name string, value int) error

AddIntConstant adds the given value as an integer constant to the Python module m with the given name.

func (*Module) AddObject

func (m *Module) AddObject(name string, obj Object) error

AddObject adds the given Object to the Python module m under the given name.

NOTE: This method steals a reference to obj, AddObjectRef is preferred. Aso, if an error is returned, then AddObject does not decrement the reference count, so the caller still owns the reference.

func (*Module) AddObjectRef

func (m *Module) AddObjectRef(name string, obj Object) error

AddObjectRef adds the given Object to the Python module m under the given name. This method does not steal a reference.

func (*Module) AddStringConstant

func (m *Module) AddStringConstant(name, value string) error

AddStringConstant adds the given value as a string constant to the Python module m with the given name.

func (*Module) AddType

func (m *Module) AddType(t *Type) error

AddType adds the given Type to the Python module m. The name of the type is used as the name in the module.

func (*Module) Base

func (m *Module) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Module) CheckExact

func (m *Module) CheckExact() bool

func (*Module) Decref

func (m *Module) Decref()

Decref decrements m's reference count, m may not be nil.

func (*Module) Dict

func (m *Module) Dict() *Dict

Dict returns the Dict that implements m's namespace.

Manipulating this Dict directly is discouraged.

Return value: Borrowed Reference.

func (*Module) GetAttr

func (m *Module) GetAttr(name Object) (Object, error)

GetAttr is a convenience wrapper that is equivalent to mod.Base().GetAttr(name).

Return value: New Reference.

func (*Module) GetAttrString

func (m *Module) GetAttrString(name string) (Object, error)

GetAttrString is a convenience wrapper that is equivalent to mod.Base().GetAttrString(name).

Return value: New Reference.

func (*Module) Incref

func (m *Module) Incref()

Incref increments m's reference count, m may not be nil.

func (*Module) Name

func (m *Module) Name() (string, error)

Name returns the name of the Python module m.

func (*Module) Register

func (m *Module) Register() error

Register adds the Python module to the importer for the embedded Python. This makes the module available for import by Python code using the module name.

func (*Module) Type

func (m *Module) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type ModuleDef

type ModuleDef struct {
	Name    string
	Doc     string
	Package bool
	Methods []GoMethod
}

ModuleDef defines a Python module. Name is the module name (including any parent packages, separated by ., e.g. "foo.bar"), Doc is the module docsring, Package should be set to true to make the module a package (a module that can have sub-modules), and Methods defined the module's methods.

The definition can be turned into an actual module using py.CreateModule, and registered for importing in embedded Python using the Module's Register method.

type NoneObject

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

NoneObject is the type of the None value. The only value of this type is None.

func (*NoneObject) Base

func (n *NoneObject) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*NoneObject) Decref

func (n *NoneObject) Decref()

Decref is a nop, since NoneObject values are immortal.

func (*NoneObject) Incref

func (n *NoneObject) Incref()

Incref is a nop, since NoneObject values are immortal.

func (*NoneObject) String

func (*NoneObject) String() string

String returns a string representation of the NoneObject type. This function always returns "None".

func (*NoneObject) Type

func (n *NoneObject) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type NumberMethods

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

NumberMethods is a concrete realisation of the full set of Number Protocol methods. A type that implements the "Number Protocol" can be turned into a NumberMethods instance using AsNumber.

Note that the methods not already implemented on the type itself may return an error, as not all methods are implemented by all types that support the protocol.

func AsNumberMethods

func AsNumberMethods(obj Object) *NumberMethods

AsNumberMethods returns a NumberMethods instance that refers to the same underlying Python object as obj. If obj doesn't implement the "Number Protocol" (i.e. the Number interface), then nil is returned.

This method is more complete than the NumberProtocol interface, as it will also work with unknown or dynamic types that implement the "Number Protocol".

func (*NumberMethods) Absolute

func (n *NumberMethods) Absolute() (Object, error)

Absolute returns the absolute value of n. The equivalent Python is "abs(n)".

Return value: New Reference.

func (*NumberMethods) Add

func (n *NumberMethods) Add(obj Object) (Object, error)

Add returns the result of adding n and obj. The equivalent Python is "n + obj".

Return value: New Reference.

func (*NumberMethods) And

func (n *NumberMethods) And(obj Object) (Object, error)

And returns the bitwise and of n and obj. The equivalent Python is "n & obj".

Return value: New Reference.

func (*NumberMethods) AsInt

func (n *NumberMethods) AsInt(exc *ExceptionClass) (int, error)

PyNumber_AsSsize_t: TODO

func (*NumberMethods) AsNumberMethods

func (n *NumberMethods) AsNumberMethods() *NumberMethods

AsNumberMethods simply returns n. This ensures however that NumberMethods implements NumberProtocol.

func (*NumberMethods) Base

func (n *NumberMethods) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*NumberMethods) Decref

func (n *NumberMethods) Decref()

Decref decrements n's reference count, n may not be nil.

func (*NumberMethods) Divmod

func (n *NumberMethods) Divmod(obj Object) (Object, error)

Divmod returns the result of the Python "divmod(n, obj)".

Return value: New Reference.

func (*NumberMethods) Float

func (n *NumberMethods) Float() (*Float, error)

PyNumber_Float: TODO

func (*NumberMethods) FloorDivide

func (n *NumberMethods) FloorDivide(obj Object) (Object, error)

FloorDivide returns the floor of dividing n by obj. The equivalent Python is "n // obj".

Return value: New Reference.

func (*NumberMethods) InPlaceAdd

func (n *NumberMethods) InPlaceAdd(obj Object) (Object, error)

InPlaceAdd returns the result of adding n and obj. This is done in place if supported by n. The equivalent Python is "n += obj".

Return value: New Reference.

func (*NumberMethods) InPlaceAnd

func (n *NumberMethods) InPlaceAnd(obj Object) (Object, error)

InPlaceAnd returns the bitwise and of n and obj. This is done in place if supported by n. The equivalent Python is "n &= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceFloorDivide

func (n *NumberMethods) InPlaceFloorDivide(obj Object) (Object, error)

InPlaceFloorDivide returns the floor of dividing n by obj. This is done in place if supported by n. The equivalent Python is "n //= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceLShift

func (n *NumberMethods) InPlaceLShift(obj Object) (Object, error)

InPlaceLShift returns the result of left shifting n by obj. This is done in place if supported by n. The equivalent Python is "n <<= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceMultiply

func (n *NumberMethods) InPlaceMultiply(obj Object) (Object, error)

InPlaceMultiply returns the result of multiplying n by obj. This is done in place if supported by n. The equivalent Python is "n *= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceOr

func (n *NumberMethods) InPlaceOr(obj Object) (Object, error)

InPlaceOr returns the bitwise or of n and obj. This is done in place if supported by n. The equivalent Python is "n |= obj".

Return value: New Reference.

func (*NumberMethods) InPlacePower

func (n *NumberMethods) InPlacePower(obj1, obj2 Object) (Object, error)

InPlacePower returns the result of the Python "pow(n, obj1, obj2)". This is done in place if supported by n. If obj2 is None, then the Python "n **= obj" is also equivalent, if obj2 is not None, there is no equivalent in Python.

Return value: New Reference.

func (*NumberMethods) InPlaceRShift

func (n *NumberMethods) InPlaceRShift(obj Object) (Object, error)

InPlaceRShift returns the result of right shifting n by obj. This is done in place if supported by n. The equivalent Python is "n >>= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceRemainder

func (n *NumberMethods) InPlaceRemainder(obj Object) (Object, error)

InPlaceRemainder returns the remainder of n divided by obj. This is done in place if supported by n. The equivalent Python is "n %= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceSubtract

func (n *NumberMethods) InPlaceSubtract(obj Object) (Object, error)

InPlaceSubtract returns the result of subtracting obj from n. This is done in place if supported by n. The equivalent Python is "n -= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceTrueDivide

func (n *NumberMethods) InPlaceTrueDivide(obj Object) (Object, error)

InPlaceTrueDivide returns the approximate result of dividing n by obj. This is done in place if supported by n. The result is approximate due to the limited representational accuracy of binary floating point numbers. The equivalent Python is "n /= obj".

Return value: New Reference.

func (*NumberMethods) InPlaceXor

func (n *NumberMethods) InPlaceXor(obj Object) (Object, error)

InPlaceXor returns the bitwise xor of n and obj. This is done in place if supported by n. The equivalent Python is "n ^= obj".

Return value: New Reference.

func (*NumberMethods) Incref

func (n *NumberMethods) Incref()

Incref increments n's reference count, n may not be nil.

func (*NumberMethods) Index

func (n *NumberMethods) Index() (*Long, error)

PyNumber_Index: TODO

func (*NumberMethods) Invert

func (n *NumberMethods) Invert() (Object, error)

Invert returns the bitwise negation of n. The equivalent Python is "-n".

Return value: New Reference.

func (*NumberMethods) LShift

func (n *NumberMethods) LShift(obj Object) (Object, error)

LShift returns the result of left shifting n by obj. The equivalent Python is "n << obj".

Return value: New Reference.

func (*NumberMethods) Long

func (n *NumberMethods) Long() (*Long, error)

PyNumber_Long: TODO

func (*NumberMethods) Multiply

func (n *NumberMethods) Multiply(obj Object) (Object, error)

Multiply returns the result of multiplying n by obj. The equivalent Python is "n * obj".

Return value: New Reference.

func (*NumberMethods) Negative

func (n *NumberMethods) Negative() (Object, error)

Negative returns the negation of n. The equivalent Python is "-n".

Return value: New Reference.

func (*NumberMethods) Or

func (n *NumberMethods) Or(obj Object) (Object, error)

Or returns the bitwise or of n and obj. The equivalent Python is "n | obj".

Return value: New Reference.

func (*NumberMethods) Positive

func (n *NumberMethods) Positive() (Object, error)

Positive returns the positive of n. The equivalent Python is "+n".

Return value: New Reference.

func (*NumberMethods) Power

func (n *NumberMethods) Power(obj1, obj2 Object) (Object, error)

Power returns the result of the Python "pow(n, obj1, obj2)".

Return value: New Reference.

func (*NumberMethods) RShift

func (n *NumberMethods) RShift(obj Object) (Object, error)

RShift returns the result of right shifting n by obj. The equivalent Python is "n << obj".

Return value: New Reference.

func (*NumberMethods) Remainder

func (n *NumberMethods) Remainder(obj Object) (Object, error)

Remainder returns the remainder of dividing n by obj. The equivalent Python is "n % obj".

Return value: New Reference.

func (*NumberMethods) Subtract

func (n *NumberMethods) Subtract(obj Object) (Object, error)

Subtract returns the result of subtracting obj from n. The equivalent Python is "n - obj".

Return value: New Reference.

func (*NumberMethods) ToBase

func (n *NumberMethods) ToBase(base int) (*Long, error)

PyNumber_ToBase: TODO

func (*NumberMethods) TrueDivide

func (n *NumberMethods) TrueDivide(obj Object) (Object, error)

TrueDivide returns the approximate result of dividing n by obj. The result is approximate due to the limited representational accuracy of binary floating point numbers. The equivalent Python is "n / obj".

Return value: New Reference.

func (*NumberMethods) Type

func (n *NumberMethods) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

func (*NumberMethods) Xor

func (n *NumberMethods) Xor(obj Object) (Object, error)

Xor returns the bitwise xor of n and obj. The equivalent Python is "n ^ obj".

Return value: New Reference.

type NumberProtocol

type NumberProtocol interface {
	Object
	AsNumberMethods() *NumberMethods
}

NumberProtocol is an interface that is implemented by types that implement the Python "Number Protocol".

type ODict

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

ODict represents objects of the ODictType (or PyODict_Type in the Python API) type.

func AsODict

func AsODict(obj Object) *ODict

AsODict casts the given obj to a ODict (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a ODict, then nil is returned.

Return value: Borrowed Reference.

func (*ODict) Base

func (o *ODict) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*ODict) Decref

func (o *ODict) Decref()

Decref decrements o's reference count, o may not be nil.

func (*ODict) DelItem

func (o *ODict) DelItem(key Object) error

func (*ODict) DelItemString

func (o *ODict) DelItemString(key string) error

func (*ODict) InPlaceOr

func (o *ODict) InPlaceOr(obj Object) (Object, error)

InPlaceOr returns the bitwise or of o and obj. This is done in place. The equivalent Python is "o |= obj".

Return value: New Reference.

func (*ODict) Incref

func (o *ODict) Incref()

Incref increments o's reference count, o may not be nil.

func (*ODict) Iter

func (o *ODict) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of o.

func (*ODict) Or

func (o *ODict) Or(obj Object) (Object, error)

Or returns the bitwise or of o and obj. The equivalent Python is "o | obj".

Return value: New Reference.

func (*ODict) Repr

func (o *ODict) Repr() (*Unicode, error)

Repr returns a String representation of "o". This is equivalent to the Python "repr(o)".

Return value: New Reference.

func (*ODict) RichCompare

func (o *ODict) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "o" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "o op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*ODict) RichCompareBool

func (o *ODict) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "o" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "o op obj", where op is the corresponding Python operator for op.

func (*ODict) SetItemString

func (o *ODict) SetItemString(key string, v Object) error

func (*ODict) Type

func (o *ODict) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Object

type Object interface {
	Base() *BaseObject
	Type() *Type
	Decref()
	Incref()
}

Object is the generic interface that represents a Python object. All of the concrete types satisfy the Object interface.

func BuildValue

func BuildValue(format string, values ...interface{}) (Object, error)

func GetBuiltins

func GetBuiltins() (Object, error)

GetBuiltins returns a dictionary of the current Python builtins.

Return value: Borrowed Reference.

func GetGlobals

func GetGlobals() (Object, error)

GetGlobals returns a dictionary of the current Python global variables.

Return value: Borrowed Reference.

func GetLocals

func GetLocals() (Object, error)

GetLocals returns a dictionary of the current Python local variables.

Return value: Borrowed Reference.

func Iterate

func Iterate(i Iterator) ([]Object, error)

Iterate will iterate through the given iterator and return the values. If an error is encountered at any point, then iteration stops, the error is returned with all values collected so far.

func NewRef

func NewRef(obj Object) Object

NewRef increments obj's reference count, and then returns obj. Obj may not be nil.

This is a convenience function for returning a new reference from a function.

func NewRefWithErr

func NewRefWithErr(obj Object, err error) (Object, error)

NewRefWithErr increments obj's reference count, and then returns obj and err. Obj may be nil.

This is a convenience function for returning a new reference from a function.

func NewValue

func NewValue(value any) (Object, error)

NewValue will try to return an appropriate Python Object for the supplied value. If the type can't be converted, then a TypeError will be returned.

If an Object is supplied, then a new reference to that Object will be returned. If value implements the AsPython interface, then the AsPython method will be called to implement the conversion.

Return value: New Reference.

func ReturnNone

func ReturnNone() Object

ReturnNone returns None. This is a deprecated convenience function for returning None from a function. Previously the reference count for None had to be incremented, but now this function adds no value, and should not be used.

Return value: New Reference.

func RichCompareNative

func RichCompareNative[T constraints.Ordered](a, b T, op Op) (Object, error)

RichCompareNative is a helper function for implementing RichCompare. Given two comparable Go values it will compare them with the requested Op and return True or False. If the op is unknown, then a ValueError will be returned.

Return value: New Reference.

func RunFile

func RunFile(filename string, start StartToken, globals, locals Object) (Object, error)

func RunString

func RunString(code string, start StartToken, globals, locals Object) (Object, error)

type Op

type Op int

Op is the type for the Python comparison operators. Used by the RichCompare functions.

type RefManager

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

RefManager is a helper for manager objects references. Objects can be added, and when Decref is called then Decref will be called on all the contained objects.

Note that RefManager is not thread-safe.

func NewRefManager

func NewRefManager() *RefManager

NewRefManager returns a new RefManager ready to use.

func (*RefManager) Add

func (r *RefManager) Add(obj Object) Object

Add adds the given object to RefManager stealing a reference.

For convenience the passed in value is returned.

Return value: Borrowed reference.

func (*RefManager) AddE

func (r *RefManager) AddE(obj Object, err error) (Object, error)

AddE adds the given object to RefManager stealing a reference. The error value is ignored (i.e. if obj and err are both != nil then obj will still be added).

For convenience the passed in values are returned.

Return value: Borrowed reference.

func (*RefManager) AddRef

func (r *RefManager) AddRef(obj Object) Object

AddRef adds the given object to RefManager. If the object is not already in the RefManager, then the reference count is also incremented.

For convenience the passed in value is returned.

Return value: Borrowed reference.

func (*RefManager) AddRefE

func (r *RefManager) AddRefE(obj Object, err error) (Object, error)

AddRefE adds the given object to RefManager. If the object is not already in the RefManager, then the reference count is also incremented. The error value is ignored (i.e. if obj and err are both != nil then obj will still be added).

For convenience the passed in values are returned.

Return value: Borrowed reference.

func (*RefManager) AllAll

func (r *RefManager) AllAll(objects ...Object)

AddAll adds the given objects to RefManager, stealing references.

func (*RefManager) AllAllRef

func (r *RefManager) AllAllRef(objects ...Object)

AddAllRef adds the given objects to RefManager. If an object is not already in the RefManager, then the reference count is also incremented.

func (*RefManager) Clear

func (r *RefManager) Clear()

Clear empties the RefManager without changing the references.

This can be called between Adding item and calling Decref, to prevent Decref from taking any action.

func (*RefManager) Decref

func (r *RefManager) Decref()

Decref will call decref on all of the Objects stored in the RefManager. The RefManager will also be emptied, so it is ok to keep using it after the call as only objects added after the call will be tracked.

func (*RefManager) Forget

func (r *RefManager) Forget(obj Object)

Forget removes the given object from the manager. The reference held by the RefManager is forgotten (the assumption is that the caller was sharing the reference).

If obj was not in RefManager, then nothing happens.

func (*RefManager) Remove

func (r *RefManager) Remove(obj Object) Object

Remove removes the given object from the manager. The reference held by the RefManager is returned.

If obj was not in RefManager, then a new reference to obj will be returned.

Return value: New reference.

type SendResult

type SendResult int
const (
	SendReturn SendResult = C.PYGEN_RETURN
	SendError  SendResult = C.PYGEN_ERROR
	SendNext   SendResult = C.PYGEN_NEXT
)

type SequenceMethods

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

SequenceMethods is a concrete realisation of the full set of Sequence Protocol methods. A type that implements the "Sequence Protocol" can be turned into a SequenceMethods instance using AsSequence.

Note that the methods not already implemented on the type itself may return an error, as not all methods are implemented by all types that support the protocol.

func AsSequenceMethods

func AsSequenceMethods(obj Object) *SequenceMethods

AsSequenceMethods returns a SequenceMethods instance that refers to the same underlying Python object as obj. If obj doesn't implement the "Sequence Protocol", then nil is returned.

This method is more complete than the SequenceProtocol interface, as it will also work with unknown or dynamic types that implement the "Sequence Protocol".

func (*SequenceMethods) AsSequenceMethods

func (s *SequenceMethods) AsSequenceMethods() *SequenceMethods

AsSequenceMethods simply returns s. This ensures however that SequenceMethods implements SequenceProtocol.

func (*SequenceMethods) Base

func (s *SequenceMethods) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*SequenceMethods) Concat

func (s *SequenceMethods) Concat(obj Object) (Object, error)

func (*SequenceMethods) Contains

func (s *SequenceMethods) Contains(value Object) (bool, error)

func (*SequenceMethods) Count

func (s *SequenceMethods) Count(value Object) (int, error)

func (*SequenceMethods) Decref

func (s *SequenceMethods) Decref()

Decref decrements s's reference count, s may not be nil.

func (*SequenceMethods) DelItem

func (s *SequenceMethods) DelItem(i int) error

func (*SequenceMethods) DelSlice

func (s *SequenceMethods) DelSlice(i1, i2 int) error

func (*SequenceMethods) GetItem

func (s *SequenceMethods) GetItem(i int) (Object, error)

func (*SequenceMethods) GetSlice

func (s *SequenceMethods) GetSlice(i1, i2 int) (Object, error)

func (*SequenceMethods) InPlaceConcat

func (s *SequenceMethods) InPlaceConcat(obj Object) (Object, error)

func (*SequenceMethods) InPlaceRepeat

func (s *SequenceMethods) InPlaceRepeat(count int) (Object, error)

func (*SequenceMethods) Incref

func (s *SequenceMethods) Incref()

Incref increments s's reference count, s may not be nil.

func (*SequenceMethods) Index

func (s *SequenceMethods) Index(value Object) (int, error)

func (*SequenceMethods) Iter

func (s *SequenceMethods) Iter() (Iterator, error)

func (*SequenceMethods) List

func (s *SequenceMethods) List() (*List, error)

func (*SequenceMethods) Repeat

func (s *SequenceMethods) Repeat(count int) (Object, error)

func (*SequenceMethods) SetItem

func (s *SequenceMethods) SetItem(i int, v Object) error

func (*SequenceMethods) SetSlice

func (s *SequenceMethods) SetSlice(i1, i2 int, v Object) error

func (*SequenceMethods) Size

func (s *SequenceMethods) Size() (int, error)

func (*SequenceMethods) Tuple

func (s *SequenceMethods) Tuple() (*Tuple, error)

func (*SequenceMethods) Type

func (s *SequenceMethods) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type SequenceProtocol

type SequenceProtocol interface {
	Object
	AsSequenceMethods() *SequenceMethods
}

SequenceProtocol is an interface that is implemented by types that implement the Python "Sequence Protocol".

type Set

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

Set represents objects of the SetType (or PySet_Type in the Python API) type.

func AsSet

func AsSet(obj Object) *Set

AsSet casts the given obj to a Set (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Set, then nil is returned.

Return value: Borrowed Reference.

func NewSet

func NewSet(o Object) (*Set, error)

NewSet create a new Python set instance. The set contains the values from the passed Object if it is iterable (a TypeError is returned if "o" is not iterable). An empty set is returned if o is nil.

Return value: New Reference.

func (*Set) Add

func (s *Set) Add(key Object) error

Add adds "key" to the set "s". "key" must be hashable, otherwise a TypeError is returned.

func (*Set) And

func (s *Set) And(obj Object) (Object, error)

And returns the bitwise and of s and obj. The equivalent Python is "s & obj".

Return value: New Reference.

func (*Set) Base

func (s *Set) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Set) Clear

func (s *Set) Clear() error

Clear empties the set "s".

func (*Set) Contains

func (s *Set) Contains(obj Object) (bool, error)

func (*Set) Decref

func (s *Set) Decref()

Decref decrements s's reference count, s may not be nil.

func (*Set) Discard

func (s *Set) Discard(key Object) (bool, error)

Discard removes the specified "key" from the set "s". It returns true if the Object was found and removed, false if it was not found. "key" must be hashable, otherwise a TypeError is returned.

func (*Set) GetAttr

func (s *Set) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "s" with the name "name". This is equivalent to the Python "s.name".

Return value: New Reference.

func (*Set) HasAttr

func (s *Set) HasAttr(name Object) bool

HasAttr returns true if "s" has the attribute "name". This is equivalent to the Python "hasattr(s, name)".

func (*Set) Hash

func (s *Set) Hash() (int, error)

Hash computes and returns the hash value of s. The equivalent Python is "hash(s)".

func (*Set) InPlaceAnd

func (s *Set) InPlaceAnd(obj Object) (Object, error)

InPlaceAnd returns the bitwise and of s and obj. This is done in place. The equivalent Python is "s &= obj".

Return value: New Reference.

func (*Set) InPlaceOr

func (s *Set) InPlaceOr(obj Object) (Object, error)

InPlaceOr returns the bitwise or of s and obj. This is done in place. The equivalent Python is "s |= obj".

Return value: New Reference.

func (*Set) InPlaceSubtract

func (s *Set) InPlaceSubtract(obj Object) (Object, error)

InPlaceSubtract returns the result of subtracting obj from s. This is done in place. The equivalent Python is "s -= obj".

Return value: New Reference.

func (*Set) InPlaceXor

func (s *Set) InPlaceXor(obj Object) (Object, error)

InPlaceXor returns the bitwise xor of s and obj. This is done in place. The equivalent Python is "s ^= obj".

Return value: New Reference.

func (*Set) Incref

func (s *Set) Incref()

Incref increments s's reference count, s may not be nil.

func (*Set) Iter

func (s *Set) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of s.

func (*Set) Or

func (s *Set) Or(obj Object) (Object, error)

Or returns the bitwise or of s and obj. The equivalent Python is "s | obj".

Return value: New Reference.

func (*Set) Pop

func (s *Set) Pop() (Object, error)

Pop returns a new refereence to an arbitrary Object from the set, and removes it. If the set is empty a KeyError is returned.

Return value: New Reference.

func (*Set) Repr

func (s *Set) Repr() (*Unicode, error)

Repr returns a String representation of "s". This is equivalent to the Python "repr(s)".

Return value: New Reference.

func (*Set) RichCompare

func (s *Set) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "s" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "s op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Set) RichCompareBool

func (s *Set) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "s" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "s op obj", where op is the corresponding Python operator for op.

func (*Set) Size

func (s *Set) Size() int

Size returns the size of s. The equivalent Python is "len(s)".

func (*Set) Subtract

func (s *Set) Subtract(obj Object) (Object, error)

Subtract returns the result of subtracting obj from s. The equivalent Python is "s - obj".

Return value: New Reference.

func (*Set) Type

func (s *Set) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

func (*Set) Xor

func (s *Set) Xor(obj Object) (Object, error)

Xor returns the bitwise xor of s and obj. The equivalent Python is "s ^ obj".

Return value: New Reference.

type Slice

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

Slice represents objects of the SliceType (or PySlice_Type in the Python API) type.

func AsSlice

func AsSlice(obj Object) *Slice

AsSlice casts the given obj to a Slice (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Slice, then nil is returned.

Return value: Borrowed Reference.

func (*Slice) Base

func (s *Slice) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Slice) Decref

func (s *Slice) Decref()

Decref decrements s's reference count, s may not be nil.

func (*Slice) GetAttr

func (s *Slice) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "s" with the name "name". This is equivalent to the Python "s.name".

Return value: New Reference.

func (*Slice) HasAttr

func (s *Slice) HasAttr(name Object) bool

HasAttr returns true if "s" has the attribute "name". This is equivalent to the Python "hasattr(s, name)".

func (*Slice) Hash

func (s *Slice) Hash() (int, error)

Hash computes and returns the hash value of s. The equivalent Python is "hash(s)".

func (*Slice) Incref

func (s *Slice) Incref()

Incref increments s's reference count, s may not be nil.

func (*Slice) Repr

func (s *Slice) Repr() (*Unicode, error)

Repr returns a String representation of "s". This is equivalent to the Python "repr(s)".

Return value: New Reference.

func (*Slice) RichCompare

func (s *Slice) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "s" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "s op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Slice) RichCompareBool

func (s *Slice) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "s" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "s op obj", where op is the corresponding Python operator for op.

func (*Slice) Type

func (s *Slice) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type StartToken

type StartToken int
const (
	EvalInput StartToken = iota
	FileInput
	SingleInput
)

type Super

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

Super represents objects of the SuperType (or PySuper_Type in the Python API) type.

func (*Super) Base

func (s *Super) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Super) CallMethod

func (s *Super) CallMethod(name string, args *Tuple, kwds *Dict) (Object, error)

CallMethod calls the method of s called name with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "s.name(*args, **kwds)" in Python.

Return value: New Reference.

func (*Super) CallMethodGo

func (s *Super) CallMethodGo(name string, args []any, kwds map[string]any) (Object, error)

CallMethodGo calls the method of s called name with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "s.name(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*Super) Decref

func (s *Super) Decref()

Decref decrements s's reference count, s may not be nil.

func (*Super) Incref

func (s *Super) Incref()

Incref increments s's reference count, s may not be nil.

func (*Super) Type

func (s *Super) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Tuple

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

Tuple represents objects of the TupleType (or PyTuple_Type in the Python API) type.

This type implements the Mapping protocol.

This type implements the Sequence protocol.

func AsTuple

func AsTuple(obj Object) *Tuple

AsTuple casts the given obj to a Tuple (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Tuple, then nil is returned.

Return value: Borrowed Reference.

func NewTuple

func NewTuple(size int) (*Tuple, error)

NewTuple returns a new *Tuple of the specified size. However the entries are all set to NULL, so the tuple should not be shared, especially with Python code, until the entries have all been set.

Return value: New Reference.

func NewTupleFromValues

func NewTupleFromValues(values ...any) (*Tuple, error)

NewTupleFromValues creates a new Python Tuple from the supplied values. The values are converted to Objects using NewValue.

Return value: New Reference.

func PackTuple

func PackTuple(items ...Object) (*Tuple, error)

PackTuple returns a new *Tuple which contains the arguments. This tuple is ready to use. This function steals the references to the Objects.

Return value: New Reference.

func (*Tuple) AsMappingMethods

func (t *Tuple) AsMappingMethods() *MappingMethods

AsMappingMethods returns a MappingMethods instance that refers to the same underlying Python object as t.

This method also means that Tuple implements the MappingProtocol interface.

func (*Tuple) AsSequenceMethods

func (t *Tuple) AsSequenceMethods() *SequenceMethods

AsSequenceMethods returns a SequenceMethods instance that refers to the same underlying Python object as t.

This method also means that Tuple implements the SequenceProtocol interface.

func (*Tuple) Base

func (t *Tuple) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Tuple) BorrowIndex

func (t *Tuple) BorrowIndex(pos int) (Object, error)

BorrowIndex returns the Object contained in tuple t at index idx. If idx is out of bounds for t, then an IndexError will be returned.

Return value: Borrowed Reference.

func (*Tuple) CheckExact

func (t *Tuple) CheckExact() bool

CheckExact returns true if the object is actually a Tuple, not a subtype.

func (*Tuple) Concat

func (t *Tuple) Concat(obj Object) (Object, error)

func (*Tuple) Contains

func (t *Tuple) Contains(obj Object) (bool, error)

func (*Tuple) Count

func (t *Tuple) Count(obj Object) (int, error)

func (*Tuple) Decref

func (t *Tuple) Decref()

Decref decrements t's reference count, t may not be nil.

func (*Tuple) GetAttr

func (t *Tuple) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "t" with the name "name". This is equivalent to the Python "t.name".

Return value: New Reference.

func (*Tuple) GetIndex

func (t *Tuple) GetIndex(idx int) (Object, error)

func (*Tuple) GetItemString

func (t *Tuple) GetItemString(key string) (Object, error)

func (*Tuple) GetSlice

func (t *Tuple) GetSlice(start, end int) (Object, error)

func (*Tuple) HasAttr

func (t *Tuple) HasAttr(name Object) bool

HasAttr returns true if "t" has the attribute "name". This is equivalent to the Python "hasattr(t, name)".

func (*Tuple) HasKey

func (t *Tuple) HasKey(key Object) bool

func (*Tuple) HasKeyString

func (t *Tuple) HasKeyString(key string) bool

func (*Tuple) Hash

func (t *Tuple) Hash() (int, error)

Hash computes and returns the hash value of t. The equivalent Python is "hash(t)".

func (*Tuple) Incref

func (t *Tuple) Incref()

Incref increments t's reference count, t may not be nil.

func (*Tuple) Index

func (t *Tuple) Index(obj Object) (int, error)

func (*Tuple) Iter

func (t *Tuple) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of t.

func (*Tuple) List

func (t *Tuple) List() (*List, error)

func (*Tuple) Repeat

func (t *Tuple) Repeat(count int) (Object, error)

func (*Tuple) Repr

func (t *Tuple) Repr() (*Unicode, error)

Repr returns a String representation of "t". This is equivalent to the Python "repr(t)".

Return value: New Reference.

func (*Tuple) RichCompare

func (t *Tuple) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "t" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "t op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Tuple) RichCompareBool

func (t *Tuple) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "t" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "t op obj", where op is the corresponding Python operator for op.

func (*Tuple) SetIndexSteal

func (t *Tuple) SetIndexSteal(pos int, obj Object) error

SetIndexSteal sets the Object at index idx in tuple t to Object obj.

Note: This method "steals" a reference to obj, and discards a reference to the current value of idx in t (if there is one).

func (*Tuple) Size

func (t *Tuple) Size() int

Size returns the size of t. The equivalent Python is "len(t)".

func (*Tuple) Slice

func (t *Tuple) Slice() []Object

Slice returns the Tuple contents as a slice of Object.

Return value: Borrowed References.

func (*Tuple) String

func (t *Tuple) String() string

String will return a string representation of t.

func (*Tuple) Type

func (t *Tuple) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Type

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

Type represents objects of the TypeType (or PyType_Type in the Python API) type.

func AsType

func AsType(obj Object) *Type

AsType casts the given obj to a Type (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Type, then nil is returned.

Return value: Borrowed Reference.

func (*Type) Alloc

func (t *Type) Alloc(n int64) (Object, error)

func (*Type) Base

func (t *Type) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Type) Call

func (t *Type) Call(args *Tuple, kwds *Dict) (Object, error)

Call calls t with the given args and kwds. kwds may be nil, args may not (an empty Tuple must be used if no arguments are wanted). Returns the result of the call, or an Error on failure. This is equivalent to "t(*args, **kwds)" in Python.

Return value: New Reference.

func (*Type) CallGo

func (t *Type) CallGo(args []any, kwds map[string]any) (Object, error)

CallGo calls t with the given args and kwds, either may be nil. Returns the result of the call, or an Error on failure. This is equivalent to "t(*args, **kwds)" in Python.

The values are converted to Objects using NewValue. A TypeError will be returned if a value cannot be converted.

Return value: New Reference.

func (*Type) CheckExact

func (t *Type) CheckExact() bool

CheckExact returns true when "t" is an actual Type object, and not some form of subclass.

func (*Type) Decref

func (t *Type) Decref()

Decref decrements t's reference count, t may not be nil.

func (*Type) DelAttr

func (t *Type) DelAttr(name, value Object) error

DelAttr deletes the attribute with the name "name" from "t". This is equivalent to the Python "del t.name".

func (*Type) GetAttr

func (t *Type) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "t" with the name "name". This is equivalent to the Python "t.name".

Return value: New Reference.

func (*Type) HasAttr

func (t *Type) HasAttr(name Object) bool

HasAttr returns true if "t" has the attribute "name". This is equivalent to the Python "hasattr(t, name)".

func (*Type) HasFeature

func (t *Type) HasFeature(feature ClassFlags) bool

HasFeature returns true when "t" has the feature in question.

func (*Type) Incref

func (t *Type) Incref()

Incref increments t's reference count, t may not be nil.

func (*Type) Init

func (t *Type) Init(obj Object, args *Tuple, kw *Dict) error

func (*Type) IsGc

func (t *Type) IsGc() bool

IsGc returns true if the type "t" supports Cyclic Garbage Collection.

func (*Type) IsSubtype

func (t *Type) IsSubtype(t2 *Type) bool

IsSubtype returns true if "t" is a subclass of "t2".

func (*Type) Modified

func (t *Type) Modified()

Modified should be called after the attributes or base class of a Type have been changed.

func (*Type) Name

func (t *Type) Name() *Unicode

Name returns the name of the type. Equivalent to `t.__name__` in Python.

Return value: New Reference.

func (*Type) Or

func (t *Type) Or(obj Object) (Object, error)

Or returns the bitwise or of t and obj. The equivalent Python is "t | obj".

Return value: New Reference.

func (*Type) QualName

func (t *Type) QualName() *Unicode

Name returns the qualified name of the type. Equivalent to `t.__qualname__` in Python.

Return value: New Reference.

func (*Type) Repr

func (t *Type) Repr() (*Unicode, error)

Repr returns a String representation of "t". This is equivalent to the Python "repr(t)".

Return value: New Reference.

func (*Type) SetAttr

func (t *Type) SetAttr(name, value Object) error

SetAttr sets the attribute of "t" with the name "name" to "value". This is equivalent to the Python "t.name = value".

func (*Type) String

func (t *Type) String() string

func (*Type) Type

func (t *Type) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

type Unicode

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

Unicode represents objects of the UnicodeType (or PyUnicode_Type in the Python API) type.

This type implements the Mapping protocol.

This type implements the Sequence protocol.

func AsUnicode

func AsUnicode(obj Object) *Unicode

AsUnicode casts the given obj to a Unicode (i.e. the underlying Python Object is the same, just the type is changed). If the value cannot be cast to a Unicode, then nil is returned.

Return value: Borrowed Reference.

func NewUnicode

func NewUnicode(s string) (*Unicode, error)

func (*Unicode) ASCIIString

func (u *Unicode) ASCIIString() (Object, error)

func (*Unicode) AsMappingMethods

func (u *Unicode) AsMappingMethods() *MappingMethods

AsMappingMethods returns a MappingMethods instance that refers to the same underlying Python object as u.

This method also means that Unicode implements the MappingProtocol interface.

func (*Unicode) AsSequenceMethods

func (u *Unicode) AsSequenceMethods() *SequenceMethods

AsSequenceMethods returns a SequenceMethods instance that refers to the same underlying Python object as u.

This method also means that Unicode implements the SequenceProtocol interface.

func (*Unicode) AsString

func (u *Unicode) AsString() (string, error)

func (*Unicode) Base

func (u *Unicode) Base() *BaseObject

Base returns a BaseObject pointer that gives access to the generic methods on that type for this object.

func (*Unicode) CharmapString

func (u *Unicode) CharmapString(mapping Object) (Object, error)

func (*Unicode) Compare

func (u *Unicode) Compare(right Object) (int, error)

func (*Unicode) Concat

func (u *Unicode) Concat(obj Object) (Object, error)

func (*Unicode) Contains

func (u *Unicode) Contains(obj Object) (bool, error)

func (*Unicode) Count

func (u *Unicode) Count(obj Object) (int, error)

func (*Unicode) CountInRange

func (u *Unicode) CountInRange(substr Object, start, end int64) (int64, error)

func (*Unicode) Decref

func (u *Unicode) Decref()

Decref decrements u's reference count, u may not be nil.

func (*Unicode) Encode

func (u *Unicode) Encode(encoding, errors string) (Object, error)

func (*Unicode) EncodeString

func (u *Unicode) EncodeString(encoding, errors string) (Object, error)

func (*Unicode) Find

func (u *Unicode) Find(substr Object, start, end int64, direction int) (int64, bool, error)

func (*Unicode) Format

func (u *Unicode) Format(args *Tuple) (*Unicode, error)

func (*Unicode) GetAttr

func (u *Unicode) GetAttr(name Object) (Object, error)

GetAttr returns the attribute of "u" with the name "name". This is equivalent to the Python "u.name".

Return value: New Reference.

func (*Unicode) GetIndex

func (u *Unicode) GetIndex(idx int) (Object, error)

func (*Unicode) GetItemString

func (u *Unicode) GetItemString(key string) (Object, error)

func (*Unicode) GetSlice

func (u *Unicode) GetSlice(start, end int) (Object, error)

func (*Unicode) HasAttr

func (u *Unicode) HasAttr(name Object) bool

HasAttr returns true if "u" has the attribute "name". This is equivalent to the Python "hasattr(u, name)".

func (*Unicode) HasKey

func (u *Unicode) HasKey(key Object) bool

func (*Unicode) HasKeyString

func (u *Unicode) HasKeyString(key string) bool

func (*Unicode) Hash

func (u *Unicode) Hash() (int, error)

Hash computes and returns the hash value of u. The equivalent Python is "hash(u)".

func (*Unicode) Incref

func (u *Unicode) Incref()

Incref increments u's reference count, u may not be nil.

func (*Unicode) Index

func (u *Unicode) Index(obj Object) (int, error)

func (*Unicode) Iter

func (u *Unicode) Iter() (Iterator, error)

Iter returns an Iterator that will iterate over the members of u.

func (*Unicode) Join

func (u *Unicode) Join(seq Object) (Object, error)

func (*Unicode) Latin1String

func (u *Unicode) Latin1String() (Object, error)

func (*Unicode) List

func (u *Unicode) List() (*List, error)

func (*Unicode) RawUnicodeEscapeString

func (u *Unicode) RawUnicodeEscapeString() (Object, error)

func (*Unicode) Remainder

func (u *Unicode) Remainder(obj Object) (Object, error)

Remainder returns the remainder of dividing u by obj. The equivalent Python is "u % obj".

Return value: New Reference.

func (*Unicode) Repeat

func (u *Unicode) Repeat(count int) (Object, error)

func (*Unicode) Replace

func (u *Unicode) Replace(substr, replstr Object, maxcount int64) (Object, error)

func (*Unicode) Repr

func (u *Unicode) Repr() (*Unicode, error)

Repr returns a String representation of "u". This is equivalent to the Python "repr(u)".

Return value: New Reference.

func (*Unicode) RichCompare

func (u *Unicode) RichCompare(obj Object, op Op) (Object, error)

RichCompare compares "u" with "obj" using the specified operation (LE, GE etc.), and returns the result. The equivalent Python is "u op obj", where op is the corresponding Python operator for op.

Return value: New Reference.

func (*Unicode) RichCompareBool

func (u *Unicode) RichCompareBool(obj Object, op Op) (bool, error)

RichCompare compares "u" with "obj" using the specified operation (LE, GE etc.), and returns true or false. The equivalent Python is "u op obj", where op is the corresponding Python operator for op.

func (*Unicode) Size

func (u *Unicode) Size() int

Size returns the size of u. The equivalent Python is "len(u)".

func (*Unicode) Split

func (u *Unicode) Split(sep Object, maxsplit int64) (Object, error)

func (*Unicode) Splitlines

func (u *Unicode) Splitlines(keepend bool) (Object, error)

func (*Unicode) Str

func (u *Unicode) Str() (*Unicode, error)

Str returns a String representation of "u". This is equivalent to the Python "str(u)".

Return value: New Reference.

func (*Unicode) String

func (u *Unicode) String() string

func (*Unicode) Tailmatch

func (u *Unicode) Tailmatch(substr Object, start, end int64, direction int) (bool, error)

func (*Unicode) Translate

func (u *Unicode) Translate(table Object, errors string) (Object, error)

func (*Unicode) Tuple

func (u *Unicode) Tuple() (*Tuple, error)

func (*Unicode) Type

func (u *Unicode) Type() *Type

Type returns a pointer to the Type that represents the type of this object in Python.

func (*Unicode) UTF16String

func (u *Unicode) UTF16String() (Object, error)

func (*Unicode) UTF32String

func (u *Unicode) UTF32String() (Object, error)

func (*Unicode) UTF8String

func (u *Unicode) UTF8String() (Object, error)

func (*Unicode) UnicodeEscapeString

func (u *Unicode) UnicodeEscapeString() (Object, error)

Directories

Path Synopsis
cmd
examples

Jump to

Keyboard shortcuts

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