py

package
v0.8.5 Latest Latest
Warning

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

Go to latest
Published: May 31, 2024 License: Apache-2.0 Imports: 2 Imported by: 0

README

Linking Python to Go

TODO

Demo

The _demo directory contains our demos (it start with _ to prevent the go command from compiling it):

  • hellopy: link Python to Go and say Hello world
  • clpy: compile Python code and eval.
  • callpy: call Python standard library function math.sqrt.
How to run demos

To run the demos in directory _demo, you need to set the LLGO_LIB_PYTHON environment variable first. Assuming you use Python 3.12, and the libpython3.12.so (or libpython3.12.dylib or python3.12.lib) file is in the /foo/bar directory, then you need to set LLGO_LIB_PYTHON to:

export LLGO_LIB_PYTHON=/foo/bar/python3.12

For example, /opt/homebrew/Frameworks/Python.framework/Versions/3.12/libpython3.12.dylib is a typical python lib location under macOS. So we should set it like this:

export LLGO_LIB_PYTHON=/opt/homebrew/Frameworks/Python.framework/Versions/3.12/python3.12

Then you can run the demos in directory _demo:

cd <demo-directory>  # eg. cd _demo/hellopy
llgo run .

Documentation

Index

Constants

View Source
const (
	LLGoPackage = "link: $LLGO_LIB_PYTHON"
)

Variables

This section is empty.

Functions

func ErrClear added in v0.8.2

func ErrClear()

Clear the error indicator. If the error indicator is not set, there is no effect.

func ErrPrint added in v0.8.2

func ErrPrint()

func Finalize

func Finalize()

func Initialize

func Initialize()

func InitializeEx

func InitializeEx(initsigs c.Int)

This function works like Initialize() if initsigs is 1. If initsigs is 0, it skips initialization registration of signal handlers, which might be useful when Python is embedded.

func RunSimpleFile

func RunSimpleFile(fp c.FilePtr, filename *c.Char) c.Int

func RunSimpleFileFlags

func RunSimpleFileFlags(fp c.FilePtr, filename *c.Char, flags *CompilerFlags) c.Int

func RunSimpleString

func RunSimpleString(command *c.Char) c.Int

func RunSimpleStringFlags

func RunSimpleStringFlags(command *c.Char, flags *CompilerFlags) c.Int

func SetProgramName

func SetProgramName(name *c.Char)

Types

type CompilerFlags

type CompilerFlags struct {
	CfFlags c.Int
}

llgo:type C

type InputType

type InputType c.Int
const (
	SingleInput InputType = 256 // read code from i/o
	FileInput   InputType = 257 // read code from filename
	EvalInput   InputType = 258 // read code from string

)

type Object

type Object struct {
	Unused [8]byte
}

Object represents a Python object.

func AddModule added in v0.8.2

func AddModule(name *c.Char) *Object

Return the module object corresponding to a module name. The name argument may be of the form package.module. First check the modules dictionary if there’s one there, and if not, create a new one and insert it in the modules dictionary. Return nil with an exception set on failure.

func BuildValue

func BuildValue(format *c.Char, __llgo_va_list ...any) *Object

Create a new value based on a format string similar to those accepted by the PyArg_Parse* family of functions and a sequence of values. Returns the value or nil in the case of an error; an exception will be raised if nil is returned. See https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue

func CompileString

func CompileString(str, filename *c.Char, start InputType) *Object

func CompileStringExFlags

func CompileStringExFlags(str, filename *c.Char, start InputType, flags *CompilerFlags, optimize c.Int) *Object

func CompileStringFlags

func CompileStringFlags(str, filename *c.Char, start InputType, flags *CompilerFlags) *Object

func CompileStringObject

func CompileStringObject(str *c.Char, filename *Object, start InputType, flags *CompilerFlags, optimize c.Int) *Object

Parse and compile the Python source code in str, returning the resulting code object. The start token is given by start; this can be used to constrain the code which can be compiled and should be py.EvalInput, py.FileInput, or py.SingleInput. The filename specified by filename is used to construct the code object and may appear in tracebacks or SyntaxError exception messages. This returns NULL if the code cannot be parsed or compiled.

The integer optimize specifies the optimization level of the compiler; a value of -1 selects the optimization level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; __debug__ is true), 1 (asserts are removed, __debug__ is false) or 2 (docstrings are removed too).

func EvalCode

func EvalCode(code, globals, locals *Object) *Object

This is a simplified interface to EvalCodeEx, with just the code object, and global and local variables. The other arguments are set to nil.

func EvalCodeEx

func EvalCodeEx(
	code, globals, locals *Object,
	args *Object, argcount c.Int, kws *Object, kwcount c.Int,
	defs *Object, defcount c.Int, kwdefs, closure *Object) *Object

Evaluate a precompiled code object, given a particular environment for its evaluation. This environment consists of a dictionary of global variables, a mapping object of local variables, arrays of arguments, keywords and defaults, a dictionary of default values for keyword-only arguments and a closure tuple of cells.

func Float

func Float(v float64) *Object

func FloatFromSring

func FloatFromSring(v *Object) *Object

func Import

func Import(name *Object) *Object

This is a higher-level interface that calls the current “import hook function” (with an explicit level of 0, meaning absolute import). It invokes the __import__() function from the __builtins__ of the current globals. This means that the import is done using whatever import hooks are installed in the current environment.

This function always uses absolute imports.

func ImportModule

func ImportModule(name *c.Char) *Object

This is a wrapper around py.Import which takes a const char* as an argument instead of an Object.

func List added in v0.8.2

func List(__llgo_va_list ...any) *Object

func Long added in v0.8.2

func Long(v c.Long) *Object

func LongFromCStr added in v0.8.2

func LongFromCStr(v *c.Char, pend **c.Char, base c.Int) *Object

func LongFromFloat64 added in v0.8.2

func LongFromFloat64(v float64) *Object

func LongFromUnicode added in v0.8.2

func LongFromUnicode(v *Object, base c.Int) *Object

func LongFromVoidPtr added in v0.8.2

func LongFromVoidPtr(v c.Pointer) *Object

func LongLong added in v0.8.2

func LongLong(v c.LongLong) *Object

func NewDict added in v0.8.2

func NewDict() *Object

Return a new empty dictionary, or nil on failure.

func NewFunc added in v0.8.2

func NewFunc(code, globals *Object) *Object

Return a new function object associated with the code object code. globals must be a dictionary with the global variables accessible to the function.

The function’s docstring and name are retrieved from the code object. __module__ is retrieved from globals. The argument defaults, annotations and closure are set to nil. __qualname__ is set to the same value as the code object’s co_qualname field.

func NewFuncWithQualName added in v0.8.2

func NewFuncWithQualName(code, globals, qualname *Object) *Object

As NewFunc, but also allows setting the function object’s __qualname__ attribute. qualname should be a unicode object or nil; if nil, the __qualname__ attribute is set to the same value as the code object’s co_qualname field.

func NewList added in v0.8.2

func NewList(len uintptr) *Object

Return a new list of length len on success, or nil on failure.

func NewTuple added in v0.8.2

func NewTuple(len uintptr) *Object

Return a new tuple object of size len, or nil on failure.

func Uintptr added in v0.8.2

func Uintptr(v uintptr) *Object

func Ulong added in v0.8.2

func Ulong(v c.Ulong) *Object

func UlongLong added in v0.8.2

func UlongLong(v c.UlongLong) *Object

func (*Object) CStr

func (u *Object) CStr() *c.Char

As CStrAndLen, but does not store the len.

llgo:link (*Object).CStr C.PyUnicode_AsUTF8

func (*Object) CStrAndLen added in v0.8.2

func (u *Object) CStrAndLen() (*c.Char, uintptr)

Return a pointer to the UTF-8 encoding of the Unicode object, and store the size of the encoded representation (in bytes) in size. The size argument can be nil; in this case no size will be stored. The returned buffer always has an extra null byte appended (not included in size), regardless of whether there are any other null code points.

In the case of an error, nil is returned with an exception set and no size is stored.

This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer. The buffer is deallocated and pointers to it become invalid when the Unicode object is garbage collected.

llgo:link (*Object).CStrAndLen C.PyUnicode_AsUTF8AndSize

func (*Object) Call

func (o *Object) Call(args, kwargs *Object) *Object

Call a callable Python object o, with arguments given by the tuple args, and named arguments given by the dictionary kwargs.

args must not be nil; use an empty tuple if no arguments are needed. If no named arguments are needed, kwargs can be nil.

Return the result of the call on success, or raise an exception and return nil on failure.

This is the equivalent of the Python expression: o(*args, **kwargs).

llgo:link (*Object).Call C.PyObject_Call

func (*Object) CallFunction

func (o *Object) CallFunction(format *c.Char, __llgo_va_list ...any) *Object

Call a callable Python object o, with a variable number of C arguments. The C arguments are described using a py.BuildValue style format string. The format can be nil, indicating that no arguments are provided.

Return the result of the call on success, or raise an exception and return nil on failure.

This is the equivalent of the Python expression: o(*args).

Note that if you only pass PyObject* args, (*Object).CallFunctionObjArgs is a faster alternative.

llgo:link (*Object).CallFunction C.PyObject_CallFunction

func (*Object) CallFunctionObjArgs

func (o *Object) CallFunctionObjArgs(__llgo_va_list ...any) *Object

Call a callable Python object o, with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by nil.

Return the result of the call on success, or raise an exception and return nil on failure.

This is the equivalent of the Python expression: o(arg1, arg2, ...).

llgo:link (*Object).CallFunctionObjArgs C.PyObject_CallFunctionObjArgs

func (*Object) CallMethod

func (o *Object) CallMethod(name *c.Char, format *c.Char, __llgo_va_list ...any) *Object

llgo:link (*Object).CallMethod C.PyObject_CallMethod

func (*Object) CallMethodNoArgs

func (o *Object) CallMethodNoArgs(name *Object) *Object

llgo:link (*Object).CallMethodNoArgs C.PyObject_CallMethodNoArgs

func (*Object) CallMethodObjArgs

func (o *Object) CallMethodObjArgs(name *Object, __llgo_va_list ...any) *Object

llgo:link (*Object).CallMethodObjArgs C.PyObject_CallMethodObjArgs

func (*Object) CallMethodOneArg

func (o *Object) CallMethodOneArg(name, arg *Object) *Object

llgo:link (*Object).CallMethodOneArg C.PyObject_CallMethodOneArg

func (*Object) CallNoArgs

func (o *Object) CallNoArgs() *Object

Call a callable Python object callable without any arguments. It is the most efficient way to call a callable Python object without any argument.

Return the result of the call on success, or raise an exception and return nil on failure.

llgo:link (*Object).CallNoArgs C.PyObject_CallNoArgs

func (*Object) CallObject

func (o *Object) CallObject(args *Object) *Object

Call a callable Python object o, with arguments given by the tuple args. If no arguments are needed, then args can be nil.

Return the result of the call on success, or raise an exception and return nil on failure.

This is the equivalent of the Python expression: o(*args).

llgo:link (*Object).CallObject C.PyObject_CallObject

func (*Object) CallOneArg

func (o *Object) CallOneArg(arg *Object) *Object

Call a callable Python object callable with exactly 1 positional argument arg and no keyword arguments.

Return the result of the call on success, or raise an exception and return nil on failure.

llgo:link (*Object).CallOneArg C.PyObject_CallOneArg

func (*Object) Callable

func (o *Object) Callable() c.Int

Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds.

llgo:link (*Object).Callable C.PyCallable_Check

func (*Object) CodeBytes added in v0.8.2

func (o *Object) CodeBytes() *Object

Equivalent to the Python code getattr(co, 'co_code'). Returns a strong reference to a BytesObject representing the bytecode in a code object. On error, nil is returned and an exception is raised.

This BytesObject may be created on-demand by the interpreter and does not necessarily represent the bytecode actually executed by CPython. The primary use case for this function is debuggers and profilers.

llgo:link (*Object).CodeBytes C.PyCode_GetCode

func (*Object) CodeVarnames added in v0.8.2

func (o *Object) CodeVarnames() *Object

Equivalent to the Python code getattr(co, 'co_varnames'). Returns a new reference to a TupleObject containing the names of the local variables. On error, nil is returned and an exception is raised.

llgo:link (*Object).CodeVarnames C.PyCode_GetVarnames

func (*Object) Cstr added in v0.8.3

func (u *Object) Cstr() *c.Char

Same as CStr. Provided for Go+.

llgo:link (*Object).Cstr C.PyUnicode_AsUTF8

func (*Object) DecRef

func (o *Object) DecRef()

llgo:link (*Object).DecRef C.Py_DecRef

func (*Object) DictItems added in v0.8.2

func (d *Object) DictItems() *Object

Return a ListObject containing all the items from the dictionary.

llgo:link (*Object).DictItems C.PyDict_Items

func (*Object) DictKeys added in v0.8.2

func (d *Object) DictKeys() *Object

Return a ListObject containing all the keys from the dictionary.

llgo:link (*Object).DictKeys C.PyDict_Keys

func (*Object) DictValues added in v0.8.2

func (d *Object) DictValues() *Object

Return a ListObject containing all the values from the dictionary.

llgo:link (*Object).DictValues C.PyDict_Values

func (*Object) Float64

func (o *Object) Float64() float64

llgo:link (*Object).Float64 C.PyFloat_AsDouble

func (*Object) FuncCode added in v0.8.2

func (f *Object) FuncCode() *Object

Return the code object associated with the function object op.

llgo:link (*Object).FuncCode C.PyFunction_GetCode

func (*Object) GetAttr

func (o *Object) GetAttr(attrName *Object) *Object

Retrieve an attribute named attrName from object o. Returns the attribute value on success, or nil on failure. This is the equivalent of the Python expression o.attrName.

llgo:link (*Object).GetAttr C.PyObject_GetAttr

func (*Object) GetAttrString

func (o *Object) GetAttrString(attrName *c.Char) *Object

llgo:link (*Object).GetAttrString C.PyObject_GetAttrString

func (*Object) IsTrue added in v0.8.2

func (o *Object) IsTrue() c.Int

Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.

llgo:link (*Object).IsTrue C.PyObject_IsTrue

func (*Object) ListAppend added in v0.8.2

func (l *Object) ListAppend(item *Object) c.Int

Append the object item at the end of list list. Return 0 if successful; return -1 and set an exception if unsuccessful. Analogous to list.append(item).

llgo:link (*Object).ListAppend C.PyList_Append

func (*Object) ListAsTuple added in v0.8.2

func (l *Object) ListAsTuple() *Object

Return a new tuple object containing the contents of list; equivalent to tuple(list).

llgo:link (*Object).ListAsTuple C.PyList_AsTuple

func (*Object) ListInsert added in v0.8.2

func (l *Object) ListInsert(index uintptr, item *Object) c.Int

Insert the item item into list list in front of index index. Return 0 if successful; return -1 and set an exception if unsuccessful. Analogous to list.insert(index, item).

llgo:link (*Object).ListInsert C.PyList_Insert

func (*Object) ListItem added in v0.8.2

func (l *Object) ListItem(index uintptr) *Object

Return the object at position index in the list pointed to by list. The position must be non-negative; indexing from the end of the list is not supported. If index is out of bounds (<0 or >=len(list)), return nil and set an IndexError exception.

llgo:link (*Object).ListItem C.PyList_GetItem

func (*Object) ListLen added in v0.8.2

func (l *Object) ListLen() uintptr

Return the length of the list object in list; this is equivalent to len(list) on a list object.

llgo:link (*Object).ListLen C.PyList_Size

func (*Object) ListReverse added in v0.8.2

func (l *Object) ListReverse() c.Int

Reverse the items of list in place. Return 0 on success, -1 on failure. This is the equivalent of list.reverse().

llgo:link (*Object).ListReverse C.PyList_Reverse

func (*Object) ListSetItem added in v0.8.2

func (l *Object) ListSetItem(index uintptr, item *Object) c.Int

Set the item at index index in list to item. Return 0 on success. If index is out of bounds, return -1 and set an IndexError exception.

llgo:link (*Object).ListSetItem C.PyList_SetItem

func (*Object) ListSetSlice added in v0.8.2

func (l *Object) ListSetSlice(low, high uintptr, itemlist *Object) c.Int

Set the slice of list between low and high to the contents of itemlist. Analogous to list[low:high] = itemlist. The itemlist may be NULL, indicating the assignment of an empty list (slice deletion). Return 0 on success, -1 on failure. Indexing from the end of the list is not supported.

llgo:link (*Object).ListSetSlice C.PyList_SetSlice

func (*Object) ListSlice added in v0.8.2

func (l *Object) ListSlice(low, high uintptr) *Object

Return a list of the objects in list containing the objects between low and high. Return nil and set an exception if unsuccessful. Analogous to list[low:high]. Indexing from the end of the list is not supported.

llgo:link (*Object).ListSlice C.PyList_GetSlice

func (*Object) ListSort added in v0.8.2

func (l *Object) ListSort() c.Int

Sort the items of list in place. Return 0 on success, -1 on failure. This is equivalent to list.sort().

llgo:link (*Object).ListSort C.PyList_Sort

func (*Object) Long added in v0.8.2

func (l *Object) Long() c.Long

llgo:link (*Object).Long C.PyLong_AsLong

func (*Object) LongAsFloat64 added in v0.8.2

func (l *Object) LongAsFloat64() float64

llgo:link (*Object).LongAsFloat64 C.PyLong_AsDouble

func (*Object) LongAsVoidPtr added in v0.8.2

func (l *Object) LongAsVoidPtr() c.Pointer

llgo:link (*Object).LongAsVoidPtr C.PyLong_AsVoidPtr

func (*Object) LongLong added in v0.8.2

func (l *Object) LongLong() c.LongLong

llgo:link (*Object).LongLong C.PyLong_AsLongLong

func (*Object) ModuleGetDict

func (m *Object) ModuleGetDict() *Object

Return the dictionary object that implements module’s namespace; this object is the same as the __dict__ attribute of the module object. If module is not a module object (or a subtype of a module object), SystemError is raised and nil is returned.

It is recommended extensions use other Module and Object functions rather than directly manipulate a module’s __dict__.

llgo:link (*Object).ModuleGetDict C.PyModule_GetDict

func (*Object) ModuleLoadSyms

func (m *Object) ModuleLoadSyms(__llgo_va_list ...any)

llgo:link (*Object).ModuleLoadSyms C.llgoLoadPyModSyms

func (*Object) NotTrue added in v0.8.2

func (o *Object) NotTrue() c.Int

Returns 0 if the object o is considered to be true, and 1 otherwise. This is equivalent to the Python expression not o. On failure, return -1.

llgo:link (*Object).NotTrue C.PyObject_Not

func (*Object) Str added in v0.8.2

func (o *Object) Str() *Object

Compute a string representation of object o. Returns the string representation on success, nil on failure. This is the equivalent of the Python expression str(o). Called by the str() built-in function and, therefore, by the print() function.

llgo:link (*Object).Str C.PyObject_Str

func (*Object) TupleItem added in v0.8.2

func (t *Object) TupleItem(index uintptr) *Object

Return the object at position pos in the tuple pointed to by p. If pos is negative or out of bounds, return nil and set an IndexError exception.

llgo:link (*Object).TupleItem C.PyTuple_GetItem

func (*Object) TupleLen added in v0.8.2

func (t *Object) TupleLen() uintptr

Take a pointer to a tuple object, and return the size of that tuple.

llgo:link (*Object).TupleLen C.PyTuple_Size

func (*Object) Type added in v0.8.2

func (o *Object) Type() *Object

llgo:link (*Object).Type C.PyObject_Type

func (*Object) TypeFlags added in v0.8.2

func (t *Object) TypeFlags() uint32

Return the tp_flags member of type. This function is primarily meant for use with Py_LIMITED_API; the individual flag bits are guaranteed to be stable across Python releases, but access to tp_flags itself is not part of the limited API.

llgo:link (*Object).TypeFlags C.PyType_GetFlags

func (*Object) TypeModule added in v0.8.2

func (t *Object) TypeModule() *Object

Return the module object associated with the given type when the type was created using PyType_FromModuleAndSpec().

If no module is associated with the given type, sets TypeError and returns nil.

This function is usually used to get the module in which a method is defined. Note that in such a method, Py_TYPE(self).Module() may not return the intended result. Py_TYPE(self) may be a subclass of the intended class, and subclasses are not necessarily defined in the same module as their superclass. See PyCMethod to get the class that defines the method. See ModuleByDef() for cases when PyCMethod cannot be used.

llgo:link (*Object).TypeModule C.PyType_GetModule

func (*Object) TypeName added in v0.8.2

func (t *Object) TypeName() *Object

Return the type’s name. Equivalent to getting the type’s __name__ attribute.

llgo:link (*Object).TypeName C.PyType_GetName

func (*Object) Uintptr added in v0.8.2

func (l *Object) Uintptr() uintptr

llgo:link (*Object).Uintptr C.PyLong_AsSize_t

func (*Object) Ulong added in v0.8.2

func (l *Object) Ulong() c.Ulong

llgo:link (*Object).Ulong C.PyLong_AsUnsignedLong

func (*Object) UlongLong added in v0.8.2

func (l *Object) UlongLong() c.UlongLong

llgo:link (*Object).UlongLong C.PyLong_AsUnsignedLongLong

func (*Object) Vectorcall

func (o *Object) Vectorcall(args **Object, nargs uintptr, kwnames *Object) *Object

llgo:link (*Object).Vectorcall C.PyObject_Vectorcall

func (*Object) VectorcallDict

func (o *Object) VectorcallDict(args **Object, nargs uintptr, kwdict *Object) *Object

llgo:link (*Object).VectorcallDict C.PyObject_VectorcallDict

func (*Object) VectorcallMethod

func (o *Object) VectorcallMethod(name *Object, args **Object, nargs uintptr, kwnames *Object) *Object

llgo:link (*Object).VectorcallMethod C.PyObject_VectorcallMethod

Directories

Path Synopsis
_demo

Jump to

Keyboard shortcuts

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