py

package module
v0.0.0-...-c358287 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2019 License: BSD-3-Clause Imports: 8 Imported by: 11

README

Build Status Coverage Status GoDoc

This is a fork of the original repository to add in Python 3 support and other tweaks necessary for the limetext project.

Documentation

Overview

Package py (github.com/limetext/gopy) provides access to the CPython C API. This package presents an idomatic Go interface to the CPython C API described at http://docs.python.org/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, a optional (i.e. it must be explictly 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

Currently it is not possible to write Python extensions in Go, as there is no support for producing Go shared libraries in the gc compiler suite, and no support for using shared libraries in the gccgo Go runtime.

Index

Constants

View Source
const (
	TPFLAGS_HAVE_GC  = uint32(C.Py_TPFLAGS_HAVE_GC)
	TPFLAGS_BASETYPE = uint32(C.Py_TPFLAGS_BASETYPE)
)
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)
)

Variables

View Source
var (
	BaseException          = newException(C.PyExc_BaseException)
	Exception              = newException(C.PyExc_Exception)
	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)
	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)
	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)
	// RecursionErrorInst        = newException(C.PyExc_RecursionErrorInst)
	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)
	ResourceWarning           = newException(C.PyExc_ResourceWarning)
)

BaseType is the Type object that represents the BaseObject type.

BoolType is the Type object that represents the Bool type.

CodeType is the Type object that represents the Code type.

ComplexType is the Type object that represents the Complex 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.

FloatType is the Type object that represents the Float type.

FrozenSetType is the Type object that represents the FrozenSet type.

FunctionType is the Type object that represents the Function type.

ListType is the Type object that represents the List type.

LongType is the Type object that represents the Long type.

ModuleType is the Type object that represents the Module type.

None is the Python equivalent to nil.

SetType is the Type object that represents the Set 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.

TupleType is the Type object that represents the Tuple type.

TypeType is the Type object that represents the Type type.

UnicodeType is the Type object that represents the Unicode type.

Functions

func AddToPath

func AddToPath(dir string)

func Clear

func Clear(obj Object) error

func Decref

func Decref(obj Object)

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

func EnterRecursiveCall

func EnterRecursiveCall(where string) bool

EnterRecusiveCall 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()

func Incref

func Incref(obj Object)

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

func InitThreads

func InitThreads()

func Initialize

func Initialize()

func InitializeEx

func InitializeEx(initsigs bool)

func LeaveRecursiveCall

func LeaveRecursiveCall()

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

func Main

func Main(args []string) int

func ReleaseGil

func ReleaseGil()

Types

type AbstractObject

type AbstractObject struct{}

AbstractObject is an 0-sized type that can be embedded as the first item in concrete types to provide the Object interface functions.

func (*AbstractObject) Base

func (obj *AbstractObject) Base() *BaseObject

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

func (*AbstractObject) Decref

func (obj *AbstractObject) Decref()

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

func (*AbstractObject) Free

func (obj *AbstractObject) Free()

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

func (*AbstractObject) Incref

func (obj *AbstractObject) Incref()

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

func (*AbstractObject) Init

func (obj *AbstractObject) Init(args *Tuple, kw *Dict) error

Init initialises obj. It is equivalent to "obj.__init__(*args, **kw)" in Python.

func (*AbstractObject) IsTrue

func (obj *AbstractObject) IsTrue() bool

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

func (*AbstractObject) Not

func (obj *AbstractObject) 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 (*AbstractObject) Type

func (obj *AbstractObject) Type() *Type

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

type BaseObject

type BaseObject struct {
	AbstractObject
	// 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 (*BaseObject) Bytes

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

Bytes returns a Bytes representation of "obj". This is equivalent to the Python "bytes(obj)". In Python 2.x this method is identical to Str().

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) CallFunctionObjArgs

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

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) 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) 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) 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 retuns 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) Length

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

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

func (*BaseObject) Repr

func (obj *BaseObject) Repr() (Object, 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() (Object, error)

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

Return value: New Reference.

type Bool

type Bool struct {
	AbstractObject
	// 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 (*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) String

func (b *Bool) String() string

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

type CFunction

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

func NewCFunction

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

func (*CFunction) Call

func (f *CFunction) Call(args *Tuple, kw *Dict) (Object, error)

func (*CFunction) Flags

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

func (*CFunction) Self

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

type Class

type Class struct {
	Name    string
	Flags   uint32
	Doc     string
	Type    *Type
	Pointer interface{}
	New     func(*Type, *Tuple, *Dict) (Object, error)
}

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.

Type holds a Pointer to the Type instance for this class, this is filled in by calling Create().

Pointer 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.BaseObject as its first member. The easiest ways to set Pointer 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):

PyInit(args *py.Tuple, kwds *py.Dict) os.Error              // __init__
PyCall(args *py.Tuple, kwds *py.Dict) (py.Object, os.Error) // __call__
PyRepr() string                                             // __repr__
PyStr() string                                              // __str__
PyCompare(obj py.Object) (int, os.Error)                    // __cmp__

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

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

Methods on the Python class are implemented by methods with the Py_ prefix:

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

func (*Class) Alloc

func (class *Class) Alloc(n int64) (obj Object, err error)

Alloc is a convenience function, so that Go code can create a new Object instance.

func (*Class) Create

func (c *Class) Create() (*Type, error)

Create creates and returns a pointer to a PyTypeObject that is the Python representation of the class that has been implemented in Go.

type Code

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

func CompileFile

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

func (*Code) Eval

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

type Complex

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

func NewComplex

func NewComplex(v complex128) (*Complex, error)

func (*Complex) Complex128

func (o *Complex) Complex128() complex128

func (*Complex) String

func (c *Complex) String() string

type Dict

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

*Dict represents a Python dictionary. In addition to satisfying the Object interface, Dict pointers also have a number of methods defined - representing the PyDict_XXX functions from the Python C API.

func NewDict

func NewDict() (*Dict, error)

NewDict creates a new empty dictionary.

Return value: New Reference.

func NewDictProxy

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

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(key Object) (bool, error)

Contains Returns true if the dictionary contains the given key. This is equivalent to the Python expression "key in d".

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) DelItem

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

DelItem removes the entry with the key of "key" from the dictionary d. If "key" is not hashable, a TypeError is returned.

func (*Dict) DelItemString

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

DelItem removes the entry with the key of "key" (or rather, with a *String with the value of "key" as the key) from the dictionary d.

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)

GetItemString returns the Object from dictionary d which has the key "key" (or rather, which has a *String with the value of "key" as the key). If there is no such Object, then nil is returned (without an error).

Return value: Borrowed Reference.

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) 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) 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, val Object) error

SetItemString inserts "val" into dictionary d with the key "key" (or rather, with a *String with the value of "key" will be used as the key). If "key" is not hashable, then a TypeError will be returned.

func (*Dict) Size

func (d *Dict) Size() int64

Size returns the number of items in the dictionary d. This is equivalent to the Python "len(d)".

func (*Dict) String

func (d *Dict) String() string

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

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 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 String 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 {
	AbstractObject
	// contains filtered or unexported fields
}

func (*ExceptionClass) Err

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

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

func (*ExceptionClass) ErrV

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

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

type Float

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

func NewFloat

func NewFloat(v float64) (*Float, error)

func (*Float) Float64

func (f *Float) Float64() float64

func (*Float) String

func (f *Float) String() string

type FrozenSet

type FrozenSet struct {
	Set
}

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) CheckExact

func (f *FrozenSet) CheckExact() bool

type Function

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

*Function represents a Python function. In Python this is a function created using the "def" statement.

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) Closure

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

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

Return value: Borrowed Reference.

func (*Function) Code

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

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

Return value: Borrowed Reference.

func (*Function) Defaults

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

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

Return value: Borrowed Reference.

func (*Function) Globals

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

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

Return value: Borrowed Reference.

func (*Function) Module

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

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

Return value: Borrowed Reference.

func (*Function) SetClosure

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

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

func (*Function) SetDefaults

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

SetDefaults sets teh arguement default values for the function "fn". "o" must be either a Tuple, or None.

type GilState

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

func GilState_Ensure

func GilState_Ensure() *GilState

func (*GilState) Release

func (g *GilState) Release()

type List

type List struct {
	AbstractObject
	// contains filtered or unexported fields
}

*List represents a Python list. In addition to satisfying the Object interface, List pointers also have a number of methods defined - representing the PyList_XXX functions from the Python C API.

func NewList

func NewList(size int64) (*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().

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) CheckExact

func (l *List) CheckExact() bool

CheckExact returns true if if l is an actual Python list, and not a sub type.

func (*List) GetItem

func (l *List) GetItem(idx int64) (Object, error)

GetItem 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) GetSlice

func (l *List) GetSlice(low, high int64) (*List, error)

func (*List) Insert

func (l *List) Insert(idx int64, 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) Reverse

func (l *List) Reverse() error

func (*List) SetItem

func (l *List) SetItem(idx int64, obj Object) error

SetItem 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) SetSlice

func (l *List) SetSlice(low, high int64, items *List) error

func (*List) Size

func (l *List) Size() int64

Size returns the number of elements in the list l. This is equivalent to the Python "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

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

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.

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 runtme.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()

func InitAndLock

func InitAndLock() *Lock

InitAndLock is a convience 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 is has been released by UnblockThreads().

If this function is called without UnblockThreads() having been called, then nothing happens and the function returns immediately.

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.

func (*Lock) Unlock

func (lock *Lock) Unlock()

Unlock unlocks the lock. When it returns no calls into Python made 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 necessay to call BlockThreads() before calling Unlock(), even if UnblockThreads() has been called.

type Long

type Long struct {
	AbstractObject
	NumberProtocol
	// contains filtered or unexported fields
}

func NewLong

func NewLong(i int64) *Long

func (*Long) Int64

func (l *Long) Int64() int64

func (*Long) String

func (l *Long) String() string

type Method

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

type Module

type Module struct {
	AbstractObject
	// contains filtered or unexported fields
}

func ExecCodeModule

func ExecCodeModule(name string, code Object) (*Module, error)

func Import

func Import(name string) (*Module, error)

func InitModule

func InitModule(name string, methods []Method) (*Module, error)

func NewModule

func NewModule(name string) (*Module, error)

func (*Module) AddIntConstant

func (mod *Module) AddIntConstant(name string, value int) error

func (*Module) AddObject

func (mod *Module) AddObject(name string, obj Object) error

func (*Module) AddStringConstant

func (mod *Module) AddStringConstant(name, value string) error

func (*Module) CheckExact

func (mod *Module) CheckExact() bool

func (*Module) Dict

func (mod *Module) Dict() *Dict

func (*Module) Name

func (mod *Module) Name() (string, error)

type NoneObject

type NoneObject struct {
	AbstractObject
}

NoneObject is the type of the None value. The only value of this type is None.

func (*NoneObject) String

func (n *NoneObject) String() string

type Number

type Number interface {
	Object
	Add(obj Object) (Object, error)
	Subtract(obj Object) (Object, error)
	Multiply(obj Object) (Object, error)
	FloorDivide(obj Object) (Object, error)
	TrueDivide(obj Object) (Object, error)
	Remainder(obj Object) (Object, error)
	Divmod(obj Object) (Object, error)
	Power(obj1, obj2 Object) (Object, error)
	Negative() (Object, error)
	Positive() (Object, error)
	Absolute() (Object, error)
	Invert() (Object, error)
	Lshift(obj Object) (Object, error)
	Rshift(obj Object) (Object, error)
	And(obj Object) (Object, error)
	Xor(obj Object) (Object, error)
	Or(obj Object) (Object, error)
	InPlaceAdd(obj Object) (Object, error)
	InPlaceSubtract(obj Object) (Object, error)
	InPlaceMultiply(obj Object) (Object, error)
	InPlaceFloorDivide(obj Object) (Object, error)
	InPlaceTrueDivide(obj Object) (Object, error)
	InPlaceRemainder(obj Object) (Object, error)
	InPlacePower(obj1, obj2 Object) (Object, error)
	InPlaceLshift(obj Object) (Object, error)
	InPlaceRshift(obj Object) (Object, error)
	InPlaceAnd(obj Object) (Object, error)
	InPlaceXor(obj Object) (Object, error)
	InPlaceOr(obj Object) (Object, error)
}

Number is an interface that defines the Python "Number Protocol".

func AsNumber

func AsNumber(obj Object) Number

AsNumber returns a struct pointer that satisfies the Number interface. It will refer to the same underlying object as obj. If obj doesn't implement the "Number Protocol", then nil is returned.

type NumberProtocol

type NumberProtocol struct{}

NumberProtocol is a 0-sized type that can be embedded in concrete types after the AbstractObject to provide access to the suite of methods that Python calls the "Number Protocol".

func (*NumberProtocol) Absolute

func (n *NumberProtocol) Absolute() (Object, error)

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

Return value: New Reference.

func (*NumberProtocol) Add

func (n *NumberProtocol) 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 (*NumberProtocol) And

func (n *NumberProtocol) 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 (*NumberProtocol) Divmod

func (n *NumberProtocol) Divmod(obj Object) (Object, error)

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

Return value: New Reference.

func (*NumberProtocol) FloorDivide

func (n *NumberProtocol) FloorDivide(obj Object) (Object, error)

FloorDivide returns the floor of dividing n obj obj.

Return value: New Reference.

func (*NumberProtocol) InPlaceAdd

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceAnd

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceFloorDivide

func (n *NumberProtocol) InPlaceFloorDivide(obj Object) (Object, error)

TODO returns the ...

Return value: New Reference.

func (*NumberProtocol) InPlaceLshift

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceMultiply

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceOr

func (n *NumberProtocol) 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 (*NumberProtocol) InPlacePower

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceRemainder

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceRshift

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceSubtract

func (n *NumberProtocol) 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 (*NumberProtocol) InPlaceTrueDivide

func (n *NumberProtocol) InPlaceTrueDivide(obj Object) (Object, error)

TODO returns the ...

Return value: New Reference.

func (*NumberProtocol) InPlaceXor

func (n *NumberProtocol) 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 (*NumberProtocol) Invert

func (n *NumberProtocol) Invert() (Object, error)

Invert returns the bitwise negation of n. The equivalent Python is "-n".

Return value: New Reference.

func (*NumberProtocol) Lshift

func (n *NumberProtocol) 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 (*NumberProtocol) Multiply

func (n *NumberProtocol) 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 (*NumberProtocol) Negative

func (n *NumberProtocol) Negative() (Object, error)

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

Return value: New Reference.

func (*NumberProtocol) Or

func (n *NumberProtocol) 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 (*NumberProtocol) Positive

func (n *NumberProtocol) Positive() (Object, error)

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

Return value: New Reference.

func (*NumberProtocol) Power

func (n *NumberProtocol) Power(obj1, obj2 Object) (Object, error)

Power returns the result of the Python "pow(n, obj1, obj2)".

Return value: New Reference.

func (*NumberProtocol) Remainder

func (n *NumberProtocol) 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 (*NumberProtocol) Rshift

func (n *NumberProtocol) 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 (*NumberProtocol) Subtract

func (n *NumberProtocol) 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 (*NumberProtocol) TrueDivide

func (n *NumberProtocol) TrueDivide(obj Object) (Object, error)

TrueDivide returns the ... TODO

Return value: New Reference.

func (*NumberProtocol) Xor

func (n *NumberProtocol) 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 Object

type Object interface {
	Base() *BaseObject
	Type() *Type
	Decref()
	Incref()
	IsTrue() bool
	Not() bool
	Free()
}

Object is the generic interface that represents a Python object. All of the concrete types satisfy the Object interface.

func GetBuiltins

func GetBuiltins() (Object, error)

func GetGlobals

func GetGlobals() (Object, error)

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

type Set

type Set struct {
	AbstractObject
	// contains filtered or unexported fields
}

*Set represents a Python set. In addition to satisfying the Object interface, Set pointers also have a number of methods defined - representing the PySet_XXX functions from the Python C API.

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) Clear

func (s *Set) Clear() error

Clear empties the set "s".

func (*Set) Contains

func (s *Set) Contains(key Object) (bool, error)

Contains returns true if the set "s" contains the Object "key". "key" must be hashable, otherwise a TypeError is returned. This is equivalent to the Python "key in s".

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) 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) Size

func (s *Set) Size() int64

Size returns the number of elements in the set "s". This is equivalent to the Python "len(s)".

type StartToken

type StartToken int
const (
	EvalInput StartToken = iota
	FileInput
	SingleInput
)

type Tuple

type Tuple struct {
	AbstractObject
	// contains filtered or unexported fields
}

func NewTuple

func NewTuple(size int64) (*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 PackTuple

func PackTuple(items ...Object) (*Tuple, error)

PackTuple returns a new *Tuple which contains the arguments. This tuple is ready to use.

Return value: New Reference.

func (*Tuple) CheckExact

func (t *Tuple) CheckExact() bool

func (*Tuple) GetItem

func (t *Tuple) GetItem(pos int64) (Object, error)

func (*Tuple) GetSlice

func (t *Tuple) GetSlice(low, high int64) (*Tuple, error)

func (*Tuple) SetItem

func (t *Tuple) SetItem(pos int64, obj Object) error

func (*Tuple) Size

func (t *Tuple) Size() int64

func (*Tuple) Slice

func (t *Tuple) Slice() []Object

func (*Tuple) String

func (t *Tuple) String() string

type Type

type Type struct {
	AbstractObject
	// contains filtered or unexported fields
}

func (*Type) Alloc

func (t *Type) Alloc(n int64) (Object, error)

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) HasFeature

func (t *Type) HasFeature(feature uint32) bool

HasFeature returns true when "t" has the feature in question.

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) String

func (t *Type) String() string

type Unicode

type Unicode struct {
	AbstractObject
	// contains filtered or unexported fields
}

func NewUnicode

func NewUnicode(s string) (*Unicode, error)

func (*Unicode) Format

func (s *Unicode) Format(args *Tuple) (*Unicode, error)

func (*Unicode) String

func (s *Unicode) String() string

Jump to

Keyboard shortcuts

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