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
- Variables
- func AddToPath(dir string)
- func Clear(obj Object) error
- func Decref(obj Object)
- func EnterRecursiveCall(where string) bool
- func Finalize()
- func Incref(obj Object)
- func InitThreads()
- func Initialize()
- func InitializeEx(initsigs bool)
- func LeaveRecursiveCall()
- func Main(args []string) int
- func ReleaseGil()
- type AbstractObject
- func (obj *AbstractObject) Base() *BaseObject
- func (obj *AbstractObject) Decref()
- func (obj *AbstractObject) Free()
- func (obj *AbstractObject) Incref()
- func (obj *AbstractObject) Init(args *Tuple, kw *Dict) error
- func (obj *AbstractObject) IsTrue() bool
- func (obj *AbstractObject) Not() bool
- func (obj *AbstractObject) Type() *Type
- type BaseObject
- func (obj *BaseObject) Bytes() (Object, error)
- func (obj *BaseObject) Call(args *Tuple, kwds *Dict) (Object, error)
- func (obj *BaseObject) CallFunctionObjArgs(args ...Object) (Object, error)
- func (obj *BaseObject) CallMethodObjArgs(name string, args ...Object) (Object, error)
- func (obj *BaseObject) CallObject(args *Tuple) (Object, error)
- func (obj *BaseObject) DelAttr(name Object) error
- func (obj *BaseObject) DelAttrString(name string) error
- func (obj *BaseObject) DelItem(key Object) error
- func (obj *BaseObject) Dir() (Object, error)
- func (obj *BaseObject) GetAttr(name Object) (Object, error)
- func (obj *BaseObject) GetAttrString(name string) (Object, error)
- func (obj *BaseObject) GetItem(key Object) (Object, error)
- func (obj *BaseObject) HasAttr(name Object) bool
- func (obj *BaseObject) HasAttrString(name string) bool
- func (obj *BaseObject) IsInstance(cls Object) (bool, error)
- func (obj *BaseObject) IsSubclass(cls Object) (bool, error)
- func (obj *BaseObject) Length() (int64, error)
- func (obj *BaseObject) Repr() (Object, error)
- func (obj *BaseObject) RichCompare(obj2 Object, op Op) (Object, error)
- func (obj *BaseObject) RichCompareBool(obj2 Object, op Op) (bool, error)
- func (obj *BaseObject) SetAttr(name, value Object) error
- func (obj *BaseObject) SetAttrString(name string, value Object) error
- func (obj *BaseObject) SetItem(key, value Object) error
- func (obj *BaseObject) Size() (int64, error)
- func (obj *BaseObject) Str() (Object, error)
- type Bool
- type CFunction
- type Class
- type Code
- type Complex
- type Dict
- func (d *Dict) CheckExact() bool
- func (d *Dict) Clear()
- func (d *Dict) Contains(key Object) (bool, error)
- func (d *Dict) Copy() (Object, error)
- func (d *Dict) DelItem(key Object) error
- func (d *Dict) DelItemString(key string) error
- func (d *Dict) GetItem(key Object) (Object, error)
- func (d *Dict) GetItemString(key string) (Object, error)
- func (d *Dict) Items() (*List, error)
- func (d *Dict) Keys() (*List, error)
- func (d *Dict) Map() map[Object]Object
- func (d *Dict) MapString() (map[string]Object, error)
- func (d *Dict) Merge(o Object, override bool) error
- func (d *Dict) MergeFromSeq2(o Object, override bool) error
- func (d *Dict) SetItem(key, val Object) error
- func (d *Dict) SetItemString(key string, val Object) error
- func (d *Dict) Size() int64
- func (d *Dict) String() string
- func (d *Dict) Update(o Object) error
- func (d *Dict) Values() (*List, error)
- type Error
- type ExceptionClass
- type Float
- type FrozenSet
- type Function
- func (fn *Function) Closure() (Object, error)
- func (fn *Function) Code() (Object, error)
- func (fn *Function) Defaults() (Object, error)
- func (fn *Function) Globals() (Object, error)
- func (fn *Function) Module() (Object, error)
- func (fn *Function) SetClosure(o Object) error
- func (fn *Function) SetDefaults(o Object) error
- type GilState
- type List
- func (l *List) Append(obj Object) error
- func (l *List) CheckExact() bool
- func (l *List) GetItem(idx int64) (Object, error)
- func (l *List) GetSlice(low, high int64) (*List, error)
- func (l *List) Insert(idx int64, obj Object) error
- func (l *List) Reverse() error
- func (l *List) SetItem(idx int64, obj Object) error
- func (l *List) SetSlice(low, high int64, items *List) error
- func (l *List) Size() int64
- func (l *List) Slice() []Object
- func (l *List) Sort() error
- func (l *List) String() string
- func (l *List) Tuple() *Tuple
- type Lock
- type Long
- type Method
- type Module
- type NoneObject
- type Number
- type NumberProtocol
- func (n *NumberProtocol) Absolute() (Object, error)
- func (n *NumberProtocol) Add(obj Object) (Object, error)
- func (n *NumberProtocol) And(obj Object) (Object, error)
- func (n *NumberProtocol) Divmod(obj Object) (Object, error)
- func (n *NumberProtocol) FloorDivide(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceAdd(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceAnd(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceFloorDivide(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceLshift(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceMultiply(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceOr(obj Object) (Object, error)
- func (n *NumberProtocol) InPlacePower(obj1, obj2 Object) (Object, error)
- func (n *NumberProtocol) InPlaceRemainder(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceRshift(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceSubtract(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceTrueDivide(obj Object) (Object, error)
- func (n *NumberProtocol) InPlaceXor(obj Object) (Object, error)
- func (n *NumberProtocol) Invert() (Object, error)
- func (n *NumberProtocol) Lshift(obj Object) (Object, error)
- func (n *NumberProtocol) Multiply(obj Object) (Object, error)
- func (n *NumberProtocol) Negative() (Object, error)
- func (n *NumberProtocol) Or(obj Object) (Object, error)
- func (n *NumberProtocol) Positive() (Object, error)
- func (n *NumberProtocol) Power(obj1, obj2 Object) (Object, error)
- func (n *NumberProtocol) Remainder(obj Object) (Object, error)
- func (n *NumberProtocol) Rshift(obj Object) (Object, error)
- func (n *NumberProtocol) Subtract(obj Object) (Object, error)
- func (n *NumberProtocol) TrueDivide(obj Object) (Object, error)
- func (n *NumberProtocol) Xor(obj Object) (Object, error)
- type Object
- type Op
- type Set
- type StartToken
- type Tuple
- type Type
- func (t *Type) Alloc(n int64) (Object, error)
- func (t *Type) CheckExact() bool
- func (t *Type) HasFeature(feature uint32) bool
- func (t *Type) Init(obj Object, args *Tuple, kw *Dict) error
- func (t *Type) IsGc() bool
- func (t *Type) IsSubtype(t2 *Type) bool
- func (t *Type) Modified()
- func (t *Type) String() string
- type Unicode
Constants ¶
const ( TPFLAGS_HAVE_GC = uint32(C.Py_TPFLAGS_HAVE_GC) TPFLAGS_BASETYPE = uint32(C.Py_TPFLAGS_BASETYPE) )
Variables ¶
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) )
var BaseType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyBaseObject_Type)))
BaseType is the Type object that represents the BaseObject type.
var BoolType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyBool_Type)))
BoolType is the Type object that represents the Bool type.
var CodeType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyCode_Type)))
CodeType is the Type object that represents the Code type.
var ComplexType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyComplex_Type)))
ComplexType is the Type object that represents the Complex type.
var DictType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyDict_Type)))
DictType is the Type object that represents the Dict type.
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.
var FloatType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyFloat_Type)))
FloatType is the Type object that represents the Float type.
var FrozenSetType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyFrozenSet_Type)))
FrozenSetType is the Type object that represents the FrozenSet type.
var FunctionType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyFunction_Type)))
FunctionType is the Type object that represents the Function type.
var ListType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyList_Type)))
ListType is the Type object that represents the List type.
var LongType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyLong_Type)))
LongType is the Type object that represents the Long type.
var ModuleType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyModule_Type)))
ModuleType is the Type object that represents the Module type.
var None = (*NoneObject)(unsafe.Pointer(&C._Py_NoneStruct))
None is the Python equivalent to nil.
var SetType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPySet_Type)))
SetType is the Type object that represents the Set type.
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.
var TupleType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyTuple_Type)))
TupleType is the Type object that represents the Tuple type.
var TypeType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyType_Type)))
TypeType is the Type object that represents the Type type.
var UnicodeType = (*Type)(unsafe.Pointer(C.getBasePyType(C.GoPyUnicode_Type)))
UnicodeType is the Type object that represents the Unicode type.
Functions ¶
func EnterRecursiveCall ¶
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 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 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.
type CFunction ¶
type CFunction struct { AbstractObject // contains filtered or unexported fields }
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)
type Code ¶
type Code struct { AbstractObject // contains filtered or unexported fields }
func CompileFile ¶
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
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 NewDictProxy ¶
func (*Dict) CheckExact ¶
CheckExact returns true if d is an actual dictionary object, and not an instance of a sub type.
func (*Dict) Contains ¶
Contains Returns true if the dictionary contains the given key. This is equivalent to the Python expression "key in d".
func (*Dict) Copy ¶
Copy returns a new dictionary that contains the same key-values pairs as d.
Return value: New Reference.
func (*Dict) DelItem ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetItem inserts "val" into dictionary d with the key "key". If "key" is not hashable, then a TypeError will be returned.
func (*Dict) SetItemString ¶
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 ¶
Size returns the number of items in the dictionary d. This is equivalent to the Python "len(d)".
type Error ¶
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 ¶
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 (*Error) Error ¶
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 ¶
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 }
type FrozenSet ¶
type FrozenSet struct {
Set
}
func NewFrozenSet ¶
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 ¶
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 ¶
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 ¶
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 ¶
Code returns the code object associated with the function "fn".
Return value: Borrowed Reference.
func (*Function) Defaults ¶
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 ¶
Globals returns the globals dictionary associated with the function "fn".
Return value: Borrowed Reference.
func (*Function) Module ¶
Module returns the __module__ attribute of the function "fn".
Return value: Borrowed Reference.
func (*Function) SetClosure ¶
SetClosure sets the closure associated with function "fn". "o" must be either a Tuple of Cell objects, or None.
func (*Function) SetDefaults ¶
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
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 ¶
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 ¶
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 ¶
CheckExact returns true if if l is an actual Python list, and not a sub type.
func (*List) GetItem ¶
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) Insert ¶
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) SetItem ¶
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) Size ¶
Size returns the number of elements in the list l. This is equivalent to the Python "len(l)".
func (*List) Slice ¶
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.
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 (*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 }
type Module ¶
type Module struct { AbstractObject // contains filtered or unexported fields }
func (*Module) AddStringConstant ¶
func (*Module) CheckExact ¶
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".
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.
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 GetGlobals ¶
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 ¶
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 ¶
Add adds "key" to the set "s". "key" must be hashable, otherwise a TypeError is returned.
func (*Set) Contains ¶
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 ¶
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.
type Tuple ¶
type Tuple struct { AbstractObject // contains filtered or unexported fields }
func NewTuple ¶
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 ¶
PackTuple returns a new *Tuple which contains the arguments. This tuple is ready to use.
Return value: New Reference.
func (*Tuple) CheckExact ¶
type Type ¶
type Type struct { AbstractObject // contains filtered or unexported fields }
func (*Type) CheckExact ¶
CheckExact returns true when "t" is an actual Type object, and not some form of subclass.
func (*Type) HasFeature ¶
HasFeature returns true when "t" has the feature in question.
Source Files ¶
- abstract.go
- arg.go
- base.go
- bool.go
- cfunction.go
- cgo.go
- class.go
- class_mapping.go
- class_number.go
- class_sequence.go
- class_standard.go
- code.go
- complex.go
- dict.go
- doc.go
- err.go
- eval.go
- exc.go
- exceptions.go
- float.go
- function.go
- hack.go
- list.go
- lock.go
- long.go
- memory.go
- module.go
- number.go
- object.go
- python.go
- run.go
- set.go
- tuple.go
- type.go
- unicode.go