py

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2023 License: BSD-3-Clause Imports: 17 Imported by: 45

Documentation

Overview

Function objects

Function objects and code objects should not be confused with each other:

Function objects are created by the execution of the 'def' statement. They reference a code object in their __code__ attribute, which is a purely syntactic object, i.e. nothing more than a compiled version of some source code lines. There is one code object per source code "fragment", but each code object can be referenced by zero or many function objects depending only on how many times the 'def' statement in the source was executed so far.

Python global definitions

Index

Constants

View Source
const (
	// Masks for flags above
	CO_OPTIMIZED   = 0x0001
	CO_NEWLOCALS   = 0x0002
	CO_VARARGS     = 0x0004
	CO_VARKEYWORDS = 0x0008
	CO_NESTED      = 0x0010
	CO_GENERATOR   = 0x0020

	CO_NOFREE                  = 0x0040
	CO_GENERATOR_ALLOWED       = 0x1000
	CO_FUTURE_DIVISION         = 0x2000
	CO_FUTURE_ABSOLUTE_IMPORT  = 0x4000 // do absolute imports by default
	CO_FUTURE_WITH_STATEMENT   = 0x8000
	CO_FUTURE_PRINT_FUNCTION   = 0x10000
	CO_FUTURE_UNICODE_LITERALS = 0x20000
	CO_FUTURE_BARRY_AS_BDFL    = 0x40000

	CO_COMPILER_FLAGS_MASK = CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL

	// This value is found in the cell2arg array when the
	// associated cell variable does not correspond to an
	// argument. The maximum number of arguments is 255 (indexed
	// up to 254), so 255 work as a special flag.
	CO_CELL_NOT_AN_ARG = 255

	CO_MAXBLOCKS = 20 // Max static block nesting within a function
)
View Source
const (
	// Maximum possible Int
	IntMax = math.MaxInt64
	// Minimum possible Int
	IntMin = math.MinInt64

	// Go integer limits
	GoUintMax = ^uint(0)
	GoUintMin = 0
	GoIntMax  = int(GoUintMax >> 1)
	GoIntMin  = -GoIntMax - 1
)
View Source
const (

	// The method will be passed the type object as the first parameter
	// rather than an instance of the type. This is used to create class
	// methods, similar to what is created when using the classmethod()
	// built-in function.
	METH_CLASS = 0x0010

	// The method will be passed NULL as the first parameter rather than
	// an instance of the type. This is used to create static methods,
	// similar to what is created when using the staticmethod() built-in
	// function.
	METH_STATIC = 0x0020

	// The method will be loaded in place of existing definitions. Without
	// METH_COEXIST, the default is to skip repeated definitions. Since
	// slot wrappers are loaded before the method table, the existence of
	// a sq_contains slot, for example, would generate a wrapped method
	// named __contains__() and preclude the loading of a corresponding
	// PyCFunction with the same name. With the flag defined, the
	// PyCFunction will be loaded in place of the wrapper object and will
	// co-exist with the slot. This is helpful because calls to
	// PyCFunctions are optimized more than wrapper object calls.
	METH_COEXIST = 0x0040
)
View Source
const (
	// Set if the type object is dynamically allocated
	TPFLAGS_HEAPTYPE uint = 1 << 9

	// Set if the type allows subclassing
	TPFLAGS_BASETYPE uint = 1 << 10

	// Set if the type is 'ready' -- fully initialized
	TPFLAGS_READY uint = 1 << 12

	// Set while the type is being 'readied', to prevent recursive ready calls
	TPFLAGS_READYING uint = 1 << 13

	// Objects support garbage collection (see objimp.h)
	TPFLAGS_HAVE_GC uint = 1 << 14

	// Objects support type attribute cache
	TPFLAGS_HAVE_VERSION_TAG  uint = 1 << 18
	TPFLAGS_VALID_VERSION_TAG uint = 1 << 19

	// Type is abstract and cannot be instantiated
	TPFLAGS_IS_ABSTRACT uint = 1 << 20

	// These flags are used to determine if a type is a subclass.
	TPFLAGS_INT_SUBCLASS      uint = 1 << 23
	TPFLAGS_LONG_SUBCLASS     uint = 1 << 24
	TPFLAGS_LIST_SUBCLASS     uint = 1 << 25
	TPFLAGS_TUPLE_SUBCLASS    uint = 1 << 26
	TPFLAGS_BYTES_SUBCLASS    uint = 1 << 27
	TPFLAGS_UNICODE_SUBCLASS  uint = 1 << 28
	TPFLAGS_DICT_SUBCLASS     uint = 1 << 29
	TPFLAGS_BASE_EXC_SUBCLASS uint = 1 << 30
	TPFLAGS_TYPE_SUBCLASS     uint = 1 << 31

	TPFLAGS_DEFAULT = TPFLAGS_HAVE_VERSION_TAG
)
View Source
const NAME_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"

Variables

View Source
var (
	BoolType = NewType("bool", "bool(x) -> bool\n\nReturns True when the argument x is true, False otherwise.\nThe builtins True and False are the only two instances of the class bool.\nThe class bool is a subclass of the class int, and cannot be subclassed.")
	// Some well known bools
	False = Bool(false)
	True  = Bool(true)
)
View Source
var (
	StringDictType = NewTypeX("dict", dictDoc, DictNew, nil)
	DictType       = NewType("dict", dictDoc)
)
View Source
var (
	EllipsisTypeType = NewType("EllipsisType", "")
	Ellipsis         = EllipsisType(struct{}{})
)
View Source
var (
	// Exception heirachy
	BaseException             = ObjectType.NewTypeFlags("BaseException", "Common base class for all exceptions", ExceptionNew, nil, ObjectType.Flags|TPFLAGS_BASE_EXC_SUBCLASS)
	SystemExit                = BaseException.NewType("SystemExit", "Request to exit from the interpreter.", nil, nil)
	KeyboardInterrupt         = BaseException.NewType("KeyboardInterrupt", "Program interrupted by user.", nil, nil)
	GeneratorExit             = BaseException.NewType("GeneratorExit", "Request that a generator exit.", nil, nil)
	ExceptionType             = BaseException.NewType("Exception", "Common base class for all non-exit exceptions.", nil, nil)
	StopIteration             = ExceptionType.NewType("StopIteration", "Signal the end from iterator.__next__().", nil, nil)
	ArithmeticError           = ExceptionType.NewType("ArithmeticError", "Base class for arithmetic errors.", nil, nil)
	FloatingPointError        = ArithmeticError.NewType("FloatingPointError", "Floating point operation failed.", nil, nil)
	OverflowError             = ArithmeticError.NewType("OverflowError", "Result too large to be represented.", nil, nil)
	ZeroDivisionError         = ArithmeticError.NewType("ZeroDivisionError", "Second argument to a division or modulo operation was zero.", nil, nil)
	AssertionError            = ExceptionType.NewType("AssertionError", "Assertion failed.", nil, nil)
	AttributeError            = ExceptionType.NewType("AttributeError", "Attribute not found.", nil, nil)
	BufferError               = ExceptionType.NewType("BufferError", "Buffer error.", nil, nil)
	EOFError                  = ExceptionType.NewType("EOFError", "Read beyond end of file.", nil, nil)
	ImportError               = ExceptionType.NewType("ImportError", "Import can't find module, or can't find name in module.", nil, nil)
	LookupError               = ExceptionType.NewType("LookupError", "Base class for lookup errors.", nil, nil)
	IndexError                = LookupError.NewType("IndexError", "Sequence index out of range.", nil, nil)
	KeyError                  = LookupError.NewType("KeyError", "Mapping key not found.", nil, nil)
	MemoryError               = ExceptionType.NewType("MemoryError", "Out of memory.", nil, nil)
	NameError                 = ExceptionType.NewType("NameError", "Name not found globally.", nil, nil)
	UnboundLocalError         = NameError.NewType("UnboundLocalError", "Local name referenced but not bound to a value.", nil, nil)
	OSError                   = ExceptionType.NewType("OSError", "Base class for I/O related errors.", nil, nil)
	BlockingIOError           = OSError.NewType("BlockingIOError", "I/O operation would block.", nil, nil)
	ChildProcessError         = OSError.NewType("ChildProcessError", "Child process error.", nil, nil)
	ConnectionError           = OSError.NewType("ConnectionError", "Connection error.", nil, nil)
	BrokenPipeError           = ConnectionError.NewType("BrokenPipeError", "Broken pipe.", nil, nil)
	ConnectionAbortedError    = ConnectionError.NewType("ConnectionAbortedError", "Connection aborted.", nil, nil)
	ConnectionRefusedError    = ConnectionError.NewType("ConnectionRefusedError", "Connection refused.", nil, nil)
	ConnectionResetError      = ConnectionError.NewType("ConnectionResetError", "Connection reset.", nil, nil)
	FileExistsError           = OSError.NewType("FileExistsError", "File already exists.", nil, nil)
	FileNotFoundError         = OSError.NewType("FileNotFoundError", "File not found.", nil, nil)
	InterruptedError          = OSError.NewType("InterruptedError", "Interrupted by signal.", nil, nil)
	IsADirectoryError         = OSError.NewType("IsADirectoryError", "Operation doesn't work on directories.", nil, nil)
	NotADirectoryError        = OSError.NewType("NotADirectoryError", "Operation only works on directories.", nil, nil)
	PermissionError           = OSError.NewType("PermissionError", "Not enough permissions.", nil, nil)
	ProcessLookupError        = OSError.NewType("ProcessLookupError", "Process not found.", nil, nil)
	TimeoutError              = OSError.NewType("TimeoutError", "Timeout expired.", nil, nil)
	ReferenceError            = ExceptionType.NewType("ReferenceError", "Weak ref proxy used after referent went away.", nil, nil)
	RuntimeError              = ExceptionType.NewType("RuntimeError", "Unspecified run-time error.", nil, nil)
	NotImplementedError       = RuntimeError.NewType("NotImplementedError", "Method or function hasn't been implemented yet.", nil, nil)
	SyntaxError               = ExceptionType.NewType("SyntaxError", "Invalid syntax.", nil, nil)
	IndentationError          = SyntaxError.NewType("IndentationError", "Improper indentation.", nil, nil)
	TabError                  = IndentationError.NewType("TabError", "Improper mixture of spaces and tabs.", nil, nil)
	SystemError               = ExceptionType.NewType("SystemError", "Internal error in the Gpython interpreter.\n\nPlease report this to the Gpython maintainer, along with the traceback,\nthe Gpython version, and the hardware/OS platform and version.", nil, nil)
	TypeError                 = ExceptionType.NewType("TypeError", "Inappropriate argument type.", nil, nil)
	ValueError                = ExceptionType.NewType("ValueError", "Inappropriate argument value (of correct type).", nil, nil)
	UnicodeError              = ValueError.NewType("UnicodeError", "Unicode related error.", nil, nil)
	UnicodeDecodeError        = UnicodeError.NewType("UnicodeDecodeError", "Unicode decoding error.", nil, nil)
	UnicodeEncodeError        = UnicodeError.NewType("UnicodeEncodeError", "Unicode encoding error.", nil, nil)
	UnicodeTranslateError     = UnicodeError.NewType("UnicodeTranslateError", "Unicode translation error.", nil, nil)
	Warning                   = ExceptionType.NewType("Warning", "Base class for warning categories.", nil, nil)
	DeprecationWarning        = Warning.NewType("DeprecationWarning", "Base class for warnings about deprecated features.", nil, nil)
	PendingDeprecationWarning = Warning.NewType("PendingDeprecationWarning", "Base class for warnings about features which will be deprecated\nin the future.", nil, nil)
	RuntimeWarning            = Warning.NewType("RuntimeWarning", "Base class for warnings about dubious runtime behavior.", nil, nil)
	SyntaxWarning             = Warning.NewType("SyntaxWarning", "Base class for warnings about dubious syntax.", nil, nil)
	UserWarning               = Warning.NewType("UserWarning", "Base class for warnings generated by user code.", nil, nil)
	FutureWarning             = Warning.NewType("FutureWarning", "Base class for warnings about constructs that will change semantically\nin the future.", nil, nil)
	ImportWarning             = Warning.NewType("ImportWarning", "Base class for warnings about probable mistakes in module imports", nil, nil)
	UnicodeWarning            = Warning.NewType("UnicodeWarning", "Base class for warnings about Unicode related problems, mostly\nrelated to conversion problems.", nil, nil)
	BytesWarning              = Warning.NewType("BytesWarning", "Base class for warnings about bytes and buffer related problems, mostly\nrelated to conversion from str or comparing to str.", nil, nil)
	ResourceWarning           = Warning.NewType("ResourceWarning", "Base class for warnings about resource usage.", nil, nil)
	// Singleton exceptions
	NotImplemented Object
)
View Source
var (
	NoneTypeType = NewType("NoneType", "")
	// And the ubiquitous
	None = NoneType(struct{}{})
)
View Source
var (
	// Set in vm/eval.go - to avoid circular import
	VmEvalCode func(ctx Context, code *Code, globals, locals StringDict, args []Object, kws StringDict, defs []Object, kwdefs StringDict, closure Tuple) (retval Object, err error)
	VmRunFrame func(frame *Frame) (res Object, err error)
)
View Source
var (
	// DefaultContextOpts should be the default opts created for py.NewContext.
	// Calling this ensure that you future proof you code for suggested/default settings.
	DefaultContextOpts = func() ContextOpts {
		opts := ContextOpts{
			SysPaths: DefaultCoreSysPaths,
		}
		opts.SysPaths = append(opts.SysPaths, DefaultAuxSysPaths...)
		return opts
	}

	// NewContext is a high-level call to create a new gpython interpreter context.
	// See type Context interface.
	NewContext func(opts ContextOpts) Context

	// Compiles a python buffer into a py.Code object.
	// Returns a py.Code object or otherwise an error.
	Compile func(src, srcDesc string, mode CompileMode, flags int, dont_inherit bool) (*Code, error)
)
View Source
var BigIntType = NewType("bigint", "Holds large integers")
View Source
var BoundMethodType = NewType("boundmethod", "boundmethod object")
View Source
var BytesType = ObjectType.NewType("bytes",
	`bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
  - an iterable yielding integers in range(256)
  - a text string encoded using the specified encoding
  - any object implementing the buffer API.
  - an integer`, BytesNew, nil)
View Source
var CallIteratorType = NewType("callable_iterator", "callable_iterator type")
View Source
var CellType = NewType("cell", "cell object")
View Source
var ClassMethodType = ObjectType.NewType("classmethod",
	`classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument,
just like an instance method receives the instance.
To declare a class method, use this idiom:

  class C:
      def f(cls, arg1, arg2, ...): ...
      f = classmethod(f)

It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()).  The instance is ignored except for its class.
If a class method is called for a derived class, the derived class
object is passed as the implied first argument.

Class methods are different than C++ or Java static methods.
If you want those, see the staticmethod builtin.`, ClassMethodNew, nil)
View Source
var CodeType = NewType("code", "code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n      constants, names, varnames, filename, name, firstlineno,\n      lnotab[, freevars[, cellvars]])\n\nCreate a code object.  Not for the faint of heart.")
View Source
var ComplexType = ObjectType.NewType("complex64", "complex(real[, imag]) -> complex number\n\nCreate a complex number from a real part and an optional imaginary part.\nThis is equivalent to (real + imag*1j) where imag defaults to 0.", ComplexNew, nil)
View Source
var DefaultAuxSysPaths = []string{
	"/usr/lib/python3.4",
	"/usr/local/lib/python3.4/dist-packages",
	"/usr/lib/python3/dist-packages",
}

DefaultAuxSysPaths are secondary default search paths for module sys. This can be changed during runtime and plays nice with others using DefaultContextOpts() They are separated from the default core paths since they the more likley thing you will want to completely replace when using gpython.

View Source
var DefaultCoreSysPaths = []string{
	".",
	"lib",
}

DefaultCoreSysPaths specify default search paths for module sys This can be changed during runtime and plays nice with others using DefaultContextOpts()

View Source
var EnumerateIteratorType = NewType("enumerate_iterator", `enumerate_iterator object`)
View Source
var EnumerateType = NewTypeX("enumerate", `enumerate(iterable, start=0)

Return an enumerate object.`,
	EnumerateNew, nil)
View Source
var (
	ErrUnsupportedObjType = errors.New("unsupported obj type")
)
View Source
var FileType = NewType("file", `represents an open file`)
View Source
var FilterType = NewTypeX("filter", `filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.`,
	FilterTypeNew, nil)
View Source
var FloatType = ObjectType.NewType("float", "float(x) -> floating point number\n\nConvert a string or number to a floating point number, if possible.", FloatNew, nil)
View Source
var FrameType = NewType("frame", "Represents a stack frame")
View Source
var FrozenSetType = NewType("frozenset", "frozenset() -> empty frozenset object\nfrozenset(iterable) -> frozenset object\n\nBuild an immutable unordered collection of unique elements.")
View Source
var FunctionType = NewType("function", "A python function")
View Source
var GeneratorType = NewType("generator", "generator object")
View Source
var IntType = ObjectType.NewType("int", `
int(x=0) -> integer
int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is a number, return x.__int__().  For floating point
numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base.  The literal can be preceded by '+' or '-' and be surrounded
by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4`, IntNew, nil)
View Source
var IteratorType = NewType("iterator", "iterator type")
View Source
var ListType = ObjectType.NewType("list", "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items", ListNew, nil)
View Source
var MapType = NewTypeX("filter", `map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables.  Stops when the shortest iterable is exhausted.`,
	MapTypeNew, nil)
View Source
var MethodType = NewType("method", "method object")
View Source
var ModuleType = NewType("module", "module object")
View Source
var ObjectType = &Type{
	Name:  "object",
	Doc:   "The most base type",
	Flags: TPFLAGS_BASETYPE,
	Dict:  StringDict{},
}
View Source
var PropertyType = NewType("property", "property object")
View Source
var RangeIteratorType = NewType("range_iterator", `range_iterator object`)
View Source
var RangeType = NewTypeX("range", `range(stop) -> range object
range(start, stop[, step]) -> range object

Return a virtual sequence of numbers from start to stop by step.`,
	RangeNew, nil)
View Source
var SetType = NewTypeX("set", "set() -> new empty set object\nset(iterable) -> new set object\n\nBuild an unordered collection of unique elements.", SetNew, nil)
View Source
var SliceType = NewTypeX("slice", `slice(stop) -> slice object
"slice(stop)
slice(start, stop[, step])

Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).`, SliceNew, nil)
View Source
var StaticMethodType = ObjectType.NewType("staticmethod",
	`staticmethod(function) -> method

Convert a function to be a static method.

A static method does not receive an implicit first argument.
To declare a static method, use this idiom:

     class C:
     def f(arg1, arg2, ...): ...
     f = staticmethod(f)

It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()).  The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++.
For a more advanced concept, see the classmethod builtin.`, StaticMethodNew, nil)
View Source
var StringType = ObjectType.NewType("str",
	`str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.`, StrNew, nil)
View Source
var TracebackType = NewType("traceback", "A python traceback")
View Source
var TupleType = ObjectType.NewType("tuple", "tuple() -> empty tuple\ntuple(iterable) -> tuple initialized from iterable's items\n\nIf the argument is a tuple, the return value is the same object.", TupleNew, nil)
View Source
var ZipType = NewTypeX("zip", `zip(iter1 [,iter2 [...]]) --> zip object

Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument.  The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.`,
	ZipTypeNew, nil)

Functions

func AttributeName

func AttributeName(keyObj Object) (string, error)

AttributeName converts an Object to a string, raising a TypeError if it wasn't a String

func DebugRepr

func DebugRepr(self Object) string

DebugRepr - see Repr but returns the repr or error as a string

func DeleteAttr

func DeleteAttr(self Object, keyObj Object) error

DeleteAttr

func DeleteAttrString

func DeleteAttrString(self Object, key string) error

DeleteAttrString

func DivMod

func DivMod(a, b Object) (Object, Object, error)

DivMod two python objects together returning an Object

Will raise TypeError if can't be divmod can't be run on these objects

func ExceptionClassCheck

func ExceptionClassCheck(err Object) bool

Checks that the object passed in is a class and is an exception

func ExceptionGivenMatches

func ExceptionGivenMatches(err, exc Object) bool

Check to see if err matches exc

exc can be a tuple

Used in except statements

func FloatAsFloat64

func FloatAsFloat64(obj Object) (float64, error)

PyFloat_AsDouble

func Import added in v0.1.0

func Import(ctx Context, names ...string) error

func IndexInt

func IndexInt(a Object) (int, error)

Index the python Object returning an int

Will raise TypeError if Index can't be run on this object

or IndexError if the Int won't fit!

func IndexIntCheck

func IndexIntCheck(a Object, max int) (int, error)

As IndexInt but if index is -ve addresses it from the end

If index is out of range throws IndexError

func IsException

func IsException(exception *Type, r interface{}) bool

IsException matches the result of recover to an exception

For use to catch a single python exception from go code

It can be an instance or the class itself

func Iterate

func Iterate(obj Object, fn func(Object) bool) error

Create an iterator from obj and iterate the iterator until finished calling the function passed in on each object. The iteration is finished if the function returns true

func LoadAttr added in v0.1.0

func LoadAttr(obj Object, attrName string, dst interface{}) error

LoadAttr gets the named attribute and attempts to store it into the given destination value (based on its type).

func LoadIntsFromList added in v0.1.0

func LoadIntsFromList(list Object) ([]int64, error)

LoadIntsFromList extracts a list of ints contained given a py.List or py.Tuple

func LoadTuple added in v0.1.0

func LoadTuple(args Tuple, vars []interface{}) error

LoadTuple attempts to convert each element of the given list and store into each destination value (based on its type).

func MakeGoInt

func MakeGoInt(a Object) (int, error)

Turns a into a go int if possible

func MakeGoInt64

func MakeGoInt64(a Object) (int64, error)

Turns a into a go int64 if possible

func ObjectInit

func ObjectInit(self Object, args Tuple, kwargs StringDict) error

func ObjectIsSequence added in v0.2.0

func ObjectIsSequence(o Object) bool

Return whether the object is a sequence

func ObjectIsTrue added in v0.0.1

func ObjectIsTrue(o Object) (cmp bool, err error)

Return whether the object is True or not

func ParseTuple

func ParseTuple(args Tuple, format string, results ...*Object) error

Parse tuple only

func ParseTupleAndKeywords

func ParseTupleAndKeywords(args Tuple, kwargs StringDict, format string, kwlist []string, results ...*Object) error

ParseTupleAndKeywords

func Println added in v0.2.0

func Println(self Object, args ...string) bool

Println prints the provided strings to gpython's stdout.

func RegisterModule added in v0.1.0

func RegisterModule(module *ModuleImpl)

func ReprAsString

func ReprAsString(self Object) (string, error)

Returns object as a string

Calls Repr then makes sure the output is a string

func SequenceContains

func SequenceContains(seq, obj Object) (found bool, err error)

SequenceContains returns True if obj is in seq

func SortInPlace added in v0.1.0

func SortInPlace(l *List, kwargs StringDict, funcName string) error

SortInPlace sorts the given List in place using a stable sort. kwargs can have the keys "key" and "reverse".

func StrAsString

func StrAsString(self Object) (string, error)

Returns object as a string

Calls Str then makes sure the output is a string

func StringEscape added in v0.1.0

func StringEscape(a String, ascii bool) string

Escape the py.String

func TracebackDump

func TracebackDump(err interface{})

Dumps a traceback to stderr

func TypeDelayReady

func TypeDelayReady(t *Type)

TypeDelayReady stores the list of types to initialise

Call MakeReady when all initialised

func TypeInit

func TypeInit(cls Object, args Tuple, kwargs StringDict) error

func TypeMakeReady

func TypeMakeReady() (err error)

TypeMakeReady readies all the types

func UnpackTuple

func UnpackTuple(args Tuple, kwargs StringDict, name string, min int, max int, results ...*Object) error

Unpack the args tuple into the results

Up to the caller to set default values

Types

type BigInt

type BigInt big.Int

func BigIntCheck

func BigIntCheck(obj Object) (*BigInt, error)

Checks that obj is exactly a BigInt and returns an error if not

func BigIntCheckExact

func BigIntCheckExact(obj Object) (*BigInt, error)

Checks that obj is exactly a BigInt and returns an error if not

func ConvertToBigInt added in v0.1.0

func ConvertToBigInt(other Object) (*BigInt, bool)

Convert an Object to an BigInt

Returns ok as to whether the conversion worked or not

func (*BigInt) Float

func (a *BigInt) Float() (Float, error)

Truncates to Float

If it is outside the range of an Float it will return an error

func (*BigInt) Frexp

func (a *BigInt) Frexp() (frac float64, exp int)

Frexp produces frac and exp such that a ~= frac × 2**exp

func (*BigInt) GoInt

func (x *BigInt) GoInt() (int, error)

Truncates to go int

If it is outside the range of an go int it will return an error

func (*BigInt) GoInt64

func (x *BigInt) GoInt64() (int64, error)

Truncates to go int64

If it is outside the range of an go int64 it will return an error

func (*BigInt) Int

func (x *BigInt) Int() (Int, error)

Truncates to Int

If it is outside the range of an Int it will return an error

func (*BigInt) M__abs__

func (a *BigInt) M__abs__() (Object, error)

func (*BigInt) M__add__

func (a *BigInt) M__add__(other Object) (Object, error)

func (*BigInt) M__and__

func (a *BigInt) M__and__(other Object) (Object, error)

func (*BigInt) M__bool__

func (a *BigInt) M__bool__() (Object, error)

func (*BigInt) M__ceil__

func (a *BigInt) M__ceil__() (Object, error)

func (*BigInt) M__complex__

func (a *BigInt) M__complex__() (Object, error)

func (*BigInt) M__divmod__

func (a *BigInt) M__divmod__(other Object) (Object, Object, error)

func (*BigInt) M__eq__

func (a *BigInt) M__eq__(other Object) (Object, error)

func (*BigInt) M__float__

func (a *BigInt) M__float__() (Object, error)

func (*BigInt) M__floor__

func (a *BigInt) M__floor__() (Object, error)

func (*BigInt) M__floordiv__

func (a *BigInt) M__floordiv__(other Object) (Object, error)

func (*BigInt) M__ge__

func (a *BigInt) M__ge__(other Object) (Object, error)

func (*BigInt) M__gt__

func (a *BigInt) M__gt__(other Object) (Object, error)

func (*BigInt) M__iadd__

func (a *BigInt) M__iadd__(other Object) (Object, error)

func (*BigInt) M__iand__

func (a *BigInt) M__iand__(other Object) (Object, error)

func (*BigInt) M__ifloordiv__

func (a *BigInt) M__ifloordiv__(other Object) (Object, error)

func (*BigInt) M__ilshift__

func (a *BigInt) M__ilshift__(other Object) (Object, error)

func (*BigInt) M__imod__

func (a *BigInt) M__imod__(other Object) (Object, error)

func (*BigInt) M__imul__

func (a *BigInt) M__imul__(other Object) (Object, error)

func (*BigInt) M__index__

func (a *BigInt) M__index__() (Int, error)

func (*BigInt) M__int__

func (a *BigInt) M__int__() (Object, error)

func (*BigInt) M__invert__

func (a *BigInt) M__invert__() (Object, error)

func (*BigInt) M__ior__

func (a *BigInt) M__ior__(other Object) (Object, error)

func (*BigInt) M__ipow__

func (a *BigInt) M__ipow__(other, modulus Object) (Object, error)

func (*BigInt) M__irshift__

func (a *BigInt) M__irshift__(other Object) (Object, error)

func (*BigInt) M__isub__

func (a *BigInt) M__isub__(other Object) (Object, error)

func (*BigInt) M__itruediv__

func (a *BigInt) M__itruediv__(other Object) (Object, error)

func (*BigInt) M__ixor__

func (a *BigInt) M__ixor__(other Object) (Object, error)

func (*BigInt) M__le__

func (a *BigInt) M__le__(other Object) (Object, error)

func (*BigInt) M__lshift__

func (a *BigInt) M__lshift__(other Object) (Object, error)

func (*BigInt) M__lt__

func (a *BigInt) M__lt__(other Object) (Object, error)

func (*BigInt) M__mod__

func (a *BigInt) M__mod__(other Object) (Object, error)

func (*BigInt) M__mul__

func (a *BigInt) M__mul__(other Object) (Object, error)

func (*BigInt) M__ne__

func (a *BigInt) M__ne__(other Object) (Object, error)

func (*BigInt) M__neg__

func (a *BigInt) M__neg__() (Object, error)

func (*BigInt) M__or__

func (a *BigInt) M__or__(other Object) (Object, error)

func (*BigInt) M__pos__

func (a *BigInt) M__pos__() (Object, error)

func (*BigInt) M__pow__

func (a *BigInt) M__pow__(other, modulus Object) (Object, error)

func (*BigInt) M__radd__

func (a *BigInt) M__radd__(other Object) (Object, error)

func (*BigInt) M__rand__

func (a *BigInt) M__rand__(other Object) (Object, error)

func (*BigInt) M__rdivmod__

func (a *BigInt) M__rdivmod__(other Object) (Object, Object, error)

func (*BigInt) M__repr__

func (a *BigInt) M__repr__() (Object, error)

func (*BigInt) M__rfloordiv__

func (a *BigInt) M__rfloordiv__(other Object) (Object, error)

func (*BigInt) M__rlshift__

func (a *BigInt) M__rlshift__(other Object) (Object, error)

func (*BigInt) M__rmod__

func (a *BigInt) M__rmod__(other Object) (Object, error)

func (*BigInt) M__rmul__

func (a *BigInt) M__rmul__(other Object) (Object, error)

func (*BigInt) M__ror__

func (a *BigInt) M__ror__(other Object) (Object, error)

func (*BigInt) M__round__

func (a *BigInt) M__round__(digits Object) (Object, error)

func (*BigInt) M__rpow__

func (a *BigInt) M__rpow__(other Object) (Object, error)

func (*BigInt) M__rrshift__

func (a *BigInt) M__rrshift__(other Object) (Object, error)

func (*BigInt) M__rshift__

func (a *BigInt) M__rshift__(other Object) (Object, error)

func (*BigInt) M__rsub__

func (a *BigInt) M__rsub__(other Object) (Object, error)

func (*BigInt) M__rtruediv__

func (a *BigInt) M__rtruediv__(other Object) (Object, error)

func (*BigInt) M__rxor__

func (a *BigInt) M__rxor__(other Object) (Object, error)

func (*BigInt) M__str__

func (a *BigInt) M__str__() (Object, error)

func (*BigInt) M__sub__

func (a *BigInt) M__sub__(other Object) (Object, error)

func (*BigInt) M__truediv__

func (a *BigInt) M__truediv__(other Object) (Object, error)

func (*BigInt) M__trunc__

func (a *BigInt) M__trunc__() (Object, error)

func (*BigInt) M__xor__

func (a *BigInt) M__xor__(other Object) (Object, error)

func (*BigInt) MaybeInt

func (x *BigInt) MaybeInt() Object

MaybeInt truncates to Int if it can, otherwise returns the original BigInt

func (*BigInt) Type

func (o *BigInt) Type() *Type

Type of this BigInt object

type Bool

type Bool bool

func NewBool

func NewBool(t bool) Bool

Make a new bool - returns the canonical True and False values

func (Bool) M__bool__

func (a Bool) M__bool__() (Object, error)

func (Bool) M__eq__

func (a Bool) M__eq__(other Object) (Object, error)

func (Bool) M__index__

func (a Bool) M__index__() (Int, error)

func (Bool) M__ne__

func (a Bool) M__ne__(other Object) (Object, error)

func (Bool) M__repr__

func (a Bool) M__repr__() (Object, error)

func (Bool) M__str__

func (a Bool) M__str__() (Object, error)

func (Bool) Type

func (s Bool) Type() *Type

Type of this object

type BoundMethod

type BoundMethod struct {
	Self   Object
	Method Object
}

A python BoundMethod object

func NewBoundMethod

func NewBoundMethod(self, method Object) *BoundMethod

Define a new boundmethod

func (*BoundMethod) M__call__

func (bm *BoundMethod) M__call__(args Tuple, kwargs StringDict) (Object, error)

Call the bound method

func (*BoundMethod) Type

func (o *BoundMethod) Type() *Type

Type of this object

type Bytes

type Bytes []byte

func BytesFromObject

func BytesFromObject(x Object) (Bytes, error)

Converts an object into bytes

func (Bytes) M__add__ added in v0.2.0

func (a Bytes) M__add__(other Object) (Object, error)

func (Bytes) M__eq__

func (a Bytes) M__eq__(other Object) (Object, error)

func (Bytes) M__ge__

func (a Bytes) M__ge__(other Object) (Object, error)

func (Bytes) M__gt__

func (a Bytes) M__gt__(other Object) (Object, error)

func (Bytes) M__iadd__ added in v0.2.0

func (a Bytes) M__iadd__(other Object) (Object, error)

func (Bytes) M__le__

func (a Bytes) M__le__(other Object) (Object, error)

func (Bytes) M__lt__

func (a Bytes) M__lt__(other Object) (Object, error)

func (Bytes) M__ne__

func (a Bytes) M__ne__(other Object) (Object, error)

func (Bytes) M__repr__

func (a Bytes) M__repr__() (Object, error)

func (Bytes) M__str__

func (a Bytes) M__str__() (Object, error)

func (Bytes) Replace added in v0.2.0

func (a Bytes) Replace(args Tuple) (Object, error)

func (Bytes) Type

func (o Bytes) Type() *Type

Type of this Bytes object

type CallIterator added in v0.1.0

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

A python CallIterator object

func NewCallIterator added in v0.1.0

func NewCallIterator(callable Object, sentinel Object) *CallIterator

Define a new CallIterator

func (*CallIterator) M__iter__ added in v0.1.0

func (cit *CallIterator) M__iter__() (Object, error)

func (*CallIterator) M__next__ added in v0.1.0

func (cit *CallIterator) M__next__() (Object, error)

Get next one from the iteration

func (*CallIterator) Type added in v0.1.0

func (o *CallIterator) Type() *Type

Type of this object

type Cell

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

A python Cell object

func NewCell

func NewCell(obj Object) *Cell

Define a new cell

func (*Cell) Delete

func (c *Cell) Delete()

Delete the contents of the Cell

func (*Cell) Get

func (c *Cell) Get() Object

Fetch the contents of the Cell or nil if not set

func (*Cell) Set

func (c *Cell) Set(obj Object)

Set the contents of the Cell

func (*Cell) Type

func (o *Cell) Type() *Type

Type of this object

type ClassMethod

type ClassMethod struct {
	Callable Object
	Dict     StringDict
}

func (*ClassMethod) GetDict

func (c *ClassMethod) GetDict() StringDict

Get the Dict

func (*ClassMethod) M__get__

func (c *ClassMethod) M__get__(instance, owner Object) (Object, error)

Read a classmethod from a class which makes a bound method

func (ClassMethod) Type

func (o ClassMethod) Type() *Type

Type of this ClassMethod object

type Code

type Code struct {
	Argcount       int32    // #arguments, except *args
	Kwonlyargcount int32    // #keyword only arguments
	Nlocals        int32    // #local variables
	Stacksize      int32    // #entries needed for evaluation stack
	Flags          int32    // CO_..., see below
	Code           string   // instruction opcodes
	Consts         Tuple    // list (constants used)
	Names          []string // list of strings (names used)
	Varnames       []string // tuple of strings (local variable names)
	Freevars       []string // tuple of strings (free variable names)
	Cellvars       []string // tuple of strings (cell variable names)
	// The rest doesn't count for hash or comparisons
	Cell2arg    []byte // Maps cell vars which are arguments.
	Filename    string // unicode (where it was loaded from)
	Name        string // unicode (name, for reference)
	Firstlineno int32  // first source line number
	Lnotab      string // string (encoding addr<->lineno mapping) See Objects/lnotab_notes.txt for details.

	Weakreflist *List // to support weakrefs to code objects
}

Code object

Freevars are variables declared in the namespace where the code object was defined, they are used when closures are used - these become Cellvars in the function with a closure.

Cellvars are names of local variables referenced by functions with a closure.

func NewCode

func NewCode(argcount int32, kwonlyargcount int32,
	nlocals int32, stacksize int32, flags int32,
	code_ Object, consts_ Object, names_ Object,
	varnames_ Object, freevars_ Object, cellvars_ Object,
	filename_ Object, name_ Object, firstlineno int32,
	lnotab_ Object) *Code

Make a new code object

func (*Code) Addr2Line

func (co *Code) Addr2Line(addrq int32) int32

Use co_lnotab to compute the line number from a bytecode index, addrq. See lnotab_notes.txt for the details of the lnotab representation.

func (*Code) GetNumFree

func (co *Code) GetNumFree() int

Return number of free variables

func (*Code) M__eq__

func (co *Code) M__eq__(other Object) (Object, error)

FIXME this should be the default?

func (*Code) M__ne__

func (co *Code) M__ne__(other Object) (Object, error)

FIXME this should be the default?

func (*Code) Type

func (o *Code) Type() *Type

Type of this object

type CompileMode added in v0.1.0

type CompileMode string
const (
	ExecMode   CompileMode = "exec"   // Compile a module
	EvalMode   CompileMode = "eval"   // Compile an expression
	SingleMode CompileMode = "single" // Compile a single (interactive) statement
)

type CompileOpts added in v0.1.0

type CompileOpts struct {
	UseSysPaths bool   // If set, sys.path will be used to resolve relative pathnames
	CurDir      string // If non-empty, this is the path of the current working directory.  If empty, os.Getwd() is used.
}

CompileOpts specifies options for high-level compilation.

type CompileOut added in v0.1.0

type CompileOut struct {
	SrcPathname string // Resolved pathname the .py file that was compiled (if applicable)
	PycPathname string // Pathname of the .pyc file read and/or written (if applicable)
	FileDesc    string // Pathname to be used for a a module's "__file__" attrib
	Code        *Code  // Read/Output code object ready for execution
}

CompileOut the output of high-level compilation -- e.g. ResolveAndCompile()

type Complex

type Complex complex128

func (Complex) M__abs__

func (a Complex) M__abs__() (Object, error)

func (Complex) M__add__

func (a Complex) M__add__(other Object) (Object, error)

func (Complex) M__complex__

func (a Complex) M__complex__() (Object, error)

func (Complex) M__divmod__

func (a Complex) M__divmod__(other Object) (Object, Object, error)

func (Complex) M__eq__

func (a Complex) M__eq__(other Object) (Object, error)

func (Complex) M__float__

func (a Complex) M__float__() (Object, error)

func (Complex) M__floordiv__

func (a Complex) M__floordiv__(other Object) (Object, error)

func (Complex) M__ge__

func (a Complex) M__ge__(other Object) (Object, error)

func (Complex) M__gt__

func (a Complex) M__gt__(other Object) (Object, error)

func (Complex) M__iadd__

func (a Complex) M__iadd__(other Object) (Object, error)

func (Complex) M__ifloordiv__

func (a Complex) M__ifloordiv__(other Object) (Object, error)

func (Complex) M__imod__

func (a Complex) M__imod__(other Object) (Object, error)

func (Complex) M__imul__

func (a Complex) M__imul__(other Object) (Object, error)

func (Complex) M__int__

func (a Complex) M__int__() (Object, error)

func (Complex) M__ipow__

func (a Complex) M__ipow__(other, modulus Object) (Object, error)

func (Complex) M__isub__

func (a Complex) M__isub__(other Object) (Object, error)

func (Complex) M__itruediv__

func (a Complex) M__itruediv__(other Object) (Object, error)

func (Complex) M__le__

func (a Complex) M__le__(other Object) (Object, error)

func (Complex) M__lt__

func (a Complex) M__lt__(other Object) (Object, error)

func (Complex) M__mod__

func (a Complex) M__mod__(other Object) (Object, error)

func (Complex) M__mul__

func (a Complex) M__mul__(other Object) (Object, error)

func (Complex) M__ne__

func (a Complex) M__ne__(other Object) (Object, error)

func (Complex) M__neg__

func (a Complex) M__neg__() (Object, error)

func (Complex) M__pos__

func (a Complex) M__pos__() (Object, error)

func (Complex) M__pow__

func (a Complex) M__pow__(other, modulus Object) (Object, error)

func (Complex) M__radd__

func (a Complex) M__radd__(other Object) (Object, error)

func (Complex) M__rdivmod__

func (a Complex) M__rdivmod__(other Object) (Object, Object, error)

func (Complex) M__repr__ added in v0.0.3

func (a Complex) M__repr__() (Object, error)

func (Complex) M__rfloordiv__

func (a Complex) M__rfloordiv__(other Object) (Object, error)

func (Complex) M__rmod__

func (a Complex) M__rmod__(other Object) (Object, error)

func (Complex) M__rmul__

func (a Complex) M__rmul__(other Object) (Object, error)

func (Complex) M__rpow__

func (a Complex) M__rpow__(other Object) (Object, error)

func (Complex) M__rsub__

func (a Complex) M__rsub__(other Object) (Object, error)

func (Complex) M__rtruediv__

func (a Complex) M__rtruediv__(other Object) (Object, error)

func (Complex) M__str__ added in v0.0.3

func (a Complex) M__str__() (Object, error)

func (Complex) M__sub__

func (a Complex) M__sub__(other Object) (Object, error)

func (Complex) M__truediv__

func (a Complex) M__truediv__(other Object) (Object, error)

func (Complex) Type

func (o Complex) Type() *Type

Type of this Complex object

type Context added in v0.1.0

type Context interface {

	// Resolves then compiles (if applicable) the given file system pathname into a py.Code ready to be executed.
	ResolveAndCompile(pathname string, opts CompileOpts) (CompileOut, error)

	// Creates a new py.Module instance and initializes ModuleImpl's code in the new module (if applicable).
	ModuleInit(impl *ModuleImpl) (*Module, error)

	// RunCode is a lower-level invocation to execute the given py.Code.
	// Blocks until execution is complete.
	RunCode(code *Code, globals, locals StringDict, closure Tuple) (result Object, err error)

	// Returns the named module for this context (or an error if not found)
	GetModule(moduleName string) (*Module, error)

	// Gereric access to this context's modules / state.
	Store() *ModuleStore

	// Close signals this context is about to go out of scope and any internal resources should be released.
	// Code execution on a py.Context that has been closed will result in an error.
	Close() error

	// Done returns a signal that can be used to detect when this Context has fully closed / completed.
	// If Close() is called while execution in progress, Done() will not signal until execution is complete.
	Done() <-chan struct{}
}

Context is a gpython environment instance container, providing a high-level mechanism for multiple python interpreters to run concurrently without restriction.

Context instances maintain completely independent environments, namely the modules that have been imported and their state. Modules imported into a Context are instanced from a parent ModuleImpl. For example, since Contexts each have their own sys module instance, each can set sys.path differently and independently.

If you access a Context from multiple groutines, you are responsible that access is not concurrent, with the exception of Close() and Done().

See examples/multi-context and examples/embedding.

type ContextOpts added in v0.1.0

type ContextOpts struct {
	SysArgs  []string // sys.argv initializer
	SysPaths []string // sys.path initializer
}

ContextOpts specifies fundamental environment and input settings for creating a new py.Context

type EllipsisType

type EllipsisType struct{}

func (EllipsisType) M__bool__

func (a EllipsisType) M__bool__() (Object, error)

func (EllipsisType) M__eq__

func (a EllipsisType) M__eq__(other Object) (Object, error)

func (EllipsisType) M__ne__

func (a EllipsisType) M__ne__(other Object) (Object, error)

func (EllipsisType) M__repr__

func (a EllipsisType) M__repr__() (Object, error)

func (EllipsisType) Type

func (s EllipsisType) Type() *Type

Type of this object

type Enumerate added in v0.1.0

type Enumerate struct {
	Iterable Object
	Start    Int
}

A python Enumerate object

func (*Enumerate) M__iter__ added in v0.1.0

func (e *Enumerate) M__iter__() (Object, error)

Enumerate iterator

func (*Enumerate) Type added in v0.1.0

func (e *Enumerate) Type() *Type

Type of this object

type EnumerateIterator added in v0.1.0

type EnumerateIterator struct {
	Enumerate
	Index Int
}

A python Enumerate iterator

func (*EnumerateIterator) M__iter__ added in v0.1.0

func (ei *EnumerateIterator) M__iter__() (Object, error)

EnumerateIterator iterator

func (*EnumerateIterator) M__next__ added in v0.1.0

func (ei *EnumerateIterator) M__next__() (Object, error)

EnumerateIterator iterator next

func (*EnumerateIterator) Type added in v0.1.0

func (ei *EnumerateIterator) Type() *Type

Type of this object

type Exception

type Exception struct {
	Base            *Type
	Args            Object
	Traceback       Object
	Context         Object
	Cause           Object
	SuppressContext bool
	Dict            StringDict // anything else that we want to stuff in
}

A python Exception object

func ExceptionNewf

func ExceptionNewf(metatype *Type, format string, a ...interface{}) *Exception

ExceptionNewf - make a new exception with fmt parameters

func MakeException

func MakeException(r interface{}) *Exception

Coerce an object into an exception instance one way or another

func MakeSyntaxError

func MakeSyntaxError(r interface{}, filename string, lineno int, offset int, line string) *Exception

First calls MakeException then adds the extra details in to make it a SyntaxError

func (*Exception) Error

func (e *Exception) Error() string

Go error interface

func (*Exception) M__getattr__

func (e *Exception) M__getattr__(name string) (Object, error)

FIXME prototype __getattr__ before we do introspection!

func (*Exception) M__repr__ added in v0.2.0

func (e *Exception) M__repr__() (Object, error)

func (*Exception) M__str__ added in v0.2.0

func (e *Exception) M__str__() (Object, error)

func (*Exception) Type

func (e *Exception) Type() *Type

Type of this object

type ExceptionInfo

type ExceptionInfo struct {
	Type      *Type
	Value     Object
	Traceback *Traceback
}

A python exception info block

func (ExceptionInfo) Error

func (e ExceptionInfo) Error() string

Go error interface

func (*ExceptionInfo) IsSet

func (exc *ExceptionInfo) IsSet() bool

Test for being set

func (*ExceptionInfo) TracebackDump

func (exc *ExceptionInfo) TracebackDump(w io.Writer)

Dump a traceback for exc to w

type File

type File struct {
	*os.File
	FileMode
}

func (*File) Can added in v0.0.3

func (o *File) Can(mode FileMode) bool

func (*File) Close added in v0.0.3

func (o *File) Close() (Object, error)

func (*File) Flush added in v0.0.3

func (o *File) Flush() (Object, error)

func (*File) M__enter__ added in v0.0.3

func (o *File) M__enter__() (Object, error)

func (*File) M__exit__ added in v0.0.3

func (o *File) M__exit__(exc_type, exc_value, traceback Object) (Object, error)

func (*File) Read added in v0.0.3

func (o *File) Read(args Tuple, kwargs StringDict) (Object, error)

func (*File) Type

func (o *File) Type() *Type

Type of this object

func (*File) Write added in v0.0.3

func (o *File) Write(value Object) (Object, error)

type FileMode added in v0.0.3

type FileMode int
const (
	FileRead   FileMode = 0x01
	FileWrite  FileMode = 0x02
	FileText   FileMode = 0x4000
	FileBinary FileMode = 0x8000

	FileReadWrite = FileRead + FileWrite
)

func FileModeFrom added in v0.2.0

func FileModeFrom(mode string) (perm FileMode, trunc, excl bool, err error)

type Filter added in v0.2.0

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

A python Filter object

func (*Filter) M__iter__ added in v0.2.0

func (f *Filter) M__iter__() (Object, error)

func (*Filter) M__next__ added in v0.2.0

func (f *Filter) M__next__() (Object, error)

func (*Filter) Type added in v0.2.0

func (f *Filter) Type() *Type

Type of this object

type Float

type Float float64

func FloatCheck

func FloatCheck(obj Object) (Float, error)

Returns the float value of obj if it is a float subclass

func FloatCheckExact

func FloatCheckExact(obj Object) (Float, error)

Returns the float value of obj if it is exactly a float

func (Float) M__abs__

func (a Float) M__abs__() (Object, error)

func (Float) M__add__

func (a Float) M__add__(other Object) (Object, error)

func (Float) M__bool__

func (a Float) M__bool__() (Object, error)

func (Float) M__complex__

func (a Float) M__complex__() (Object, error)

func (Float) M__divmod__

func (a Float) M__divmod__(other Object) (Object, Object, error)

func (Float) M__eq__

func (a Float) M__eq__(other Object) (Object, error)

func (Float) M__float__

func (a Float) M__float__() (Object, error)

func (Float) M__floordiv__

func (a Float) M__floordiv__(other Object) (Object, error)

func (Float) M__ge__

func (a Float) M__ge__(other Object) (Object, error)

func (Float) M__gt__

func (a Float) M__gt__(other Object) (Object, error)

func (Float) M__iadd__

func (a Float) M__iadd__(other Object) (Object, error)

func (Float) M__ifloordiv__

func (a Float) M__ifloordiv__(other Object) (Object, error)

func (Float) M__imod__

func (a Float) M__imod__(other Object) (Object, error)

func (Float) M__imul__

func (a Float) M__imul__(other Object) (Object, error)

func (Float) M__int__

func (a Float) M__int__() (Object, error)

func (Float) M__ipow__

func (a Float) M__ipow__(other, modulus Object) (Object, error)

func (Float) M__isub__

func (a Float) M__isub__(other Object) (Object, error)

func (Float) M__itruediv__

func (a Float) M__itruediv__(other Object) (Object, error)

func (Float) M__le__

func (a Float) M__le__(other Object) (Object, error)

func (Float) M__lt__

func (a Float) M__lt__(other Object) (Object, error)

func (Float) M__mod__

func (a Float) M__mod__(other Object) (Object, error)

func (Float) M__mul__

func (a Float) M__mul__(other Object) (Object, error)

func (Float) M__ne__

func (a Float) M__ne__(other Object) (Object, error)

func (Float) M__neg__

func (a Float) M__neg__() (Object, error)

func (Float) M__pos__

func (a Float) M__pos__() (Object, error)

func (Float) M__pow__

func (a Float) M__pow__(other, modulus Object) (Object, error)

func (Float) M__radd__

func (a Float) M__radd__(other Object) (Object, error)

func (Float) M__rdivmod__

func (a Float) M__rdivmod__(other Object) (Object, Object, error)

func (Float) M__repr__

func (a Float) M__repr__() (Object, error)

func (Float) M__rfloordiv__

func (a Float) M__rfloordiv__(other Object) (Object, error)

func (Float) M__rmod__

func (a Float) M__rmod__(other Object) (Object, error)

func (Float) M__rmul__

func (a Float) M__rmul__(other Object) (Object, error)

func (Float) M__round__

func (a Float) M__round__(digitsObj Object) (Object, error)

func (Float) M__rpow__

func (a Float) M__rpow__(other Object) (Object, error)

func (Float) M__rsub__

func (a Float) M__rsub__(other Object) (Object, error)

func (Float) M__rtruediv__

func (a Float) M__rtruediv__(other Object) (Object, error)

func (Float) M__str__

func (a Float) M__str__() (Object, error)

func (Float) M__sub__

func (a Float) M__sub__(other Object) (Object, error)

func (Float) M__truediv__

func (a Float) M__truediv__(other Object) (Object, error)

func (Float) Type

func (o Float) Type() *Type

Type of this Float64 object

type Frame

type Frame struct {
	// Back       *Frame        // previous frame, or nil
	Context         Context    // host module (state) context
	Code            *Code      // code segment
	Builtins        StringDict // builtin symbol table
	Globals         StringDict // global symbol table
	Locals          StringDict // local symbol table
	Stack           []Object   // Valuestack
	LocalVars       Tuple      // Fast access local vars
	CellAndFreeVars Tuple      // Cellvars then Freevars Cell objects in one Tuple

	// Next free slot in f_valuestack.  Frame creation sets to f_valuestack.
	// Frame evaluation usually NULLs it, but a frame that yields sets it
	// to the current stack top.
	// Stacktop *Object
	Yielded bool // set if the function yielded, cleared otherwise

	// FIXME Tstate *PyThreadState
	Lasti int32 // Last instruction if called
	// Call PyFrame_GetLineNumber() instead of reading this field
	// directly.  As of 2.3 f_lineno is only valid when tracing is
	// active (i.e. when f_trace is set).  At other times we use
	// PyCode_Addr2Line to calculate the line from the current
	// bytecode index.
	// Lineno     int        // Current line number
	// Iblock     int        // index in f_blockstack
	// Executing  byte       // whether the frame is still executing
	Blockstack []TryBlock // for try and loop blocks
	Block      *TryBlock  // pointer to current block or nil
	Localsplus []Object   // LocalVars + CellAndFreeVars
}

A python Frame object

func NewFrame

func NewFrame(ctx Context, globals, locals StringDict, code *Code, closure Tuple) *Frame

Make a new frame for a code object

func (*Frame) FastToLocals

func (f *Frame) FastToLocals()

Merge fast locals into frame Locals

func (*Frame) LocalsToFast

func (f *Frame) LocalsToFast(clear bool)

Merge frame Locals into fast locals

func (*Frame) Lookup

func (f *Frame) Lookup(name string) (obj Object, ok bool)

Python names are looked up in three scopes

First the local scope Next the module global scope And finally the builtins

func (*Frame) LookupGlobal

func (f *Frame) LookupGlobal(name string) (obj Object, ok bool)

Python globals are looked up in two scopes

The module global scope And finally the builtins

func (*Frame) PopBlock

func (f *Frame) PopBlock()

Pop the current block off

func (*Frame) PushBlock

func (f *Frame) PushBlock(Type TryBlockType, Handler int32, Level int)

Make a new Block (try/for/while)

func (*Frame) Type

func (o *Frame) Type() *Type

Type of this object

type FrozenSet

type FrozenSet struct {
	Set
}

func NewFrozenSet

func NewFrozenSet() *FrozenSet

Make a new empty frozen set

func NewFrozenSetFromItems

func NewFrozenSetFromItems(items []Object) *FrozenSet

Make a new set with the items passed in

func (*FrozenSet) Type

func (o *FrozenSet) Type() *Type

Type of this FrozenSet object

type Function

type Function struct {
	Code        *Code      // A code object, the __code__ attribute
	Context     Context    // Host VM context
	Globals     StringDict // A dictionary (other mappings won't do)
	Defaults    Tuple      // NULL or a tuple
	KwDefaults  StringDict // NULL or a dict
	Closure     Tuple      // NULL or a tuple of cell objects
	Doc         Object     // The __doc__ attribute, can be anything
	Name        string     // The __name__ attribute, a string object
	Dict        StringDict // The __dict__ attribute, a dict or NULL
	Weakreflist List       // List of weak references
	Annotations StringDict // Annotations, a dict or NULL
	Qualname    string     // The qualified name
}

A python Function object

func NewFunction

func NewFunction(ctx Context, code *Code, globals StringDict, qualname string) *Function

Define a new function

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

The function’s docstring, name and __module__ are retrieved from the code object, the argument defaults and closure are set to NULL.

Allows to set the function object’s __qualname__ attribute. qualname should be a unicode object or ""; if "", the __qualname__ attribute is set to the same value as its __name__ attribute.

func (*Function) GetDict

func (f *Function) GetDict() StringDict

Get the Dict

func (*Function) M__call__

func (f *Function) M__call__(args Tuple, kwargs StringDict) (Object, error)

Call a function

func (*Function) M__get__

func (f *Function) M__get__(instance, owner Object) (Object, error)

Read a function from a class which makes a bound method

func (*Function) Type

func (o *Function) Type() *Type

Type of this object

type Generator

type Generator struct {
	// Note: gi_frame can be NULL if the generator is "finished"
	Frame *Frame

	// True if generator is being executed.
	Running bool

	// The code object backing the generator
	Code *Code

	// List of weak reference.
	Weakreflist Object
}

A python Generator object

func NewGenerator

func NewGenerator(frame *Frame) *Generator

Define a new generator

func (*Generator) Close

func (it *Generator) Close() (Object, error)

generator.close()

Raises a GeneratorExit at the point where the generator function was paused. If the generator function then raises StopIteration (by exiting normally, or due to already being closed) or GeneratorExit (by not catching the exception), close returns to its caller. If the generator yields a value, a RuntimeError is raised. If the generator raises any other exception, it is propagated to the caller. close() does nothing if the generator has already exited due to an exception or normal exit.

func (*Generator) M__iter__

func (it *Generator) M__iter__() (Object, error)

func (*Generator) M__next__

func (it *Generator) M__next__() (Object, error)

generator.__next__()

Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a __next__() method, the current yield expression always evaluates to None. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the expression_list is returned to next()‘s caller. If the generator exits without yielding another value, a StopIteration exception is raised.

This method is normally called implicitly, e.g. by a for loop, or by the built-in next() function.

func (*Generator) Send

func (it *Generator) Send(arg Object) (Object, error)

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.

func (*Generator) Throw

func (it *Generator) Throw(args Tuple, kwargs StringDict) (Object, error)

generator.throw(type[, value[, traceback]])

Raises an exception of type type at the point where generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a StopIteration exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.

func (*Generator) Type

func (o *Generator) Type() *Type

Type of this object

type IGetDict

type IGetDict interface {
	GetDict() StringDict
}

Optional interfaces

type IGoInt

type IGoInt interface {
	GoInt() (int, error)
}

type IGoInt64

type IGoInt64 interface {
	GoInt64() (int64, error)
}

type I__abs__

type I__abs__ interface {
	M__abs__() (Object, error)
}

object.__abs__(self)

type I__add__

type I__add__ interface {
	M__add__(other Object) (Object, error)
}

object.__add__(self, other)

type I__and__

type I__and__ interface {
	M__and__(other Object) (Object, error)
}

object.__and__(self, other)

type I__bool__

type I__bool__ interface {
	M__bool__() (Object, error)
}

Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true. object.__bool__(self)

type I__bytes__

type I__bytes__ interface {
	M__bytes__() (Object, error)
}

Called by bytes() to compute a byte-string representation of an object. This should return a bytes object. object.__bytes__(self)

type I__call__

type I__call__ interface {
	M__call__(args Tuple, kwargs StringDict) (Object, error)
}

Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...). object.__call__(self[, args...])

type I__ceil__

type I__ceil__ interface {
	M__ceil__() (Object, error)
}

Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to x.__ceil__(), which should return an Integral value. object.__float__(self)

type I__complex__

type I__complex__ interface {
	M__complex__() (Object, error)
}

object.__complex__(self)

type I__contains__

type I__contains__ interface {
	M__contains__(item Object) (Object, error)
}

Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.

For objects that don’t define __contains__(), the membership test first tries iteration via __iter__(), then the old sequence iteration protocol via __getitem__(), see this section in the language reference. object.__contains__(self, item)

type I__del__

type I__del__ interface {
	M__del__() (Object, error)
}

Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. Note that it is possible (though not recommended!) for the __del__() method to postpone destruction of the instance by creating a new reference to it. It may then be called at a later time when this new reference is deleted. It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.

Note del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero. Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in sys.exc_info()[2] keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in sys.last_traceback keeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the latter two situations can be resolved by storing None in sys.last_traceback. Circular references which are garbage are detected and cleaned up when the cyclic garbage collector is enabled (it’s on by default). Refer to the documentation for the gc module for more information about this topic.

Warning Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called. object.__del__(self)

type I__delattr__

type I__delattr__ interface {
	M__delattr__(name string) (Object, error)
}

Like __setattr__() but for attribute deletion instead of assignment. This should only be implemented if del obj.name is meaningful for the object. object.__delattr__(self, name)

type I__delete__

type I__delete__ interface {
	M__delete__(instance Object) (Object, error)
}

Called to delete the attribute on an instance instance of the owner class. object.__delete__(self, instance)

type I__delitem__

type I__delitem__ interface {
	M__delitem__(key Object) (Object, error)
}

Called to implement deletion of self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. The same exceptions should be raised for improper key values as for the __getitem__() method. object.__delitem__(self, key)

type I__dir__

type I__dir__ interface {
	M__dir__() (Object, error)
}

Called when dir() is called on the object. A sequence must be returned. dir() converts the returned sequence to a list and sorts it. object.__dir__(self)

type I__divmod__

type I__divmod__ interface {
	M__divmod__(other Object) (Object, Object, error)
}

object.__divmod__(self, other)

type I__enter__

type I__enter__ interface {
	M__enter__() (Object, error)
}

Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. object.__enter__(self)

type I__eq__

type I__eq__ interface {
	M__eq__(other Object) (Object, error)
}

object.__eq__(self, other)

type I__exit__

type I__exit__ interface {
	M__exit__(exc_type, exc_value, traceback Object) (Object, error)
}

Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility. object.__exit__(self, exc_type, exc_value, traceback)

type I__float__

type I__float__ interface {
	M__float__() (Object, error)
}

object.__float__(self)

type I__floor__

type I__floor__ interface {
	M__floor__() (Object, error)
}

Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__(), which should return an Integral value.

type I__floordiv__

type I__floordiv__ interface {
	M__floordiv__(other Object) (Object, error)
}

object.__floordiv__(self, other)

type I__format__

type I__format__ interface {
	M__format__(format_spec Object) (Object, error)
}

Called by the format() built-in function (and by extension, the str.format() method of class str) to produce a “formatted” string representation of an object. The format_spec argument is a string that contains a description of the formatting options desired. The interpretation of the format_spec argument is up to the type implementing __format__(), however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.

See Format Specification Mini-Language for a description of the standard formatting syntax.

The return value must be a string object. object.__format__(self, format_spec)

type I__ge__

type I__ge__ interface {
	M__ge__(other Object) (Object, error)
}

object.__ge__(self, other)

type I__get__

type I__get__ interface {
	M__get__(instance, owner Object) (Object, error)
}

Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). owner is always the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner. This method should return the (computed) attribute value or raise an AttributeError exception. object.__get__(self, instance, owner)

type I__getattr__

type I__getattr__ interface {
	M__getattr__(name string) (Object, error)
}

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __getattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control over attribute access. object.__getattr__(self, name)

type I__getattribute__

type I__getattribute__ interface {
	M__getattribute__(name string) (Object, error)
}

Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Note This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions. See Special method lookup. object.__getattribute__(self, name)

type I__getitem__

type I__getitem__ interface {
	M__getitem__(key Object) (Object, error)
}

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

Note for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence. object.__getitem__(self, key)

type I__gt__

type I__gt__ interface {
	M__gt__(other Object) (Object, error)
}

object.__gt__(self, other)

type I__hash__

type I__hash__ interface {
	M__hash__() (Object, error)
}

Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. __hash__() should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g. using exclusive or) the hash values for the components of the object that also play a part in comparison of objects.

Note hash() truncates the value returned from an object’s custom __hash__() method to the size of a Py_ssize_t. This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an object’s __hash__() must interoperate on builds of different bit sizes, be sure to check the width on all supported builds. An easy way to do this is with python -c "import sys; print(sys.hash_info.width)"

If a class does not define an __eq__() method it should not define a __hash__() operation either; if it defines __eq__() but not __hash__(), its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an __eq__() method, it should not implement __hash__(), since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).

User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).

A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None. When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable).

If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ = <ParentClass>.__hash__.

If a class that does not override __eq__() wishes to suppress hash support, it should include __hash__ = None in the class definition. A class which defines its own __hash__() that explicitly raises a TypeError would be incorrectly identified as hashable by an isinstance(obj, collections.Hashable) call.

Note By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

See also PYTHONHASHSEED.

Changed in version 3.3: Hash randomization is enabled by default. object.__hash__(self)

type I__iadd__

type I__iadd__ interface {
	M__iadd__(other Object) (Object, error)
}

object.__iadd__(self, other)

type I__iand__

type I__iand__ interface {
	M__iand__(other Object) (Object, error)
}

object.__iand__(self, other)

type I__ifloordiv__

type I__ifloordiv__ interface {
	M__ifloordiv__(other Object) (Object, error)
}

object.__ifloordiv__(self, other)

type I__ilshift__

type I__ilshift__ interface {
	M__ilshift__(other Object) (Object, error)
}

object.__ilshift__(self, other)

type I__imod__

type I__imod__ interface {
	M__imod__(other Object) (Object, error)
}

object.__imod__(self, other)

type I__imul__

type I__imul__ interface {
	M__imul__(other Object) (Object, error)
}

object.__imul__(self, other)

type I__index__

type I__index__ interface {
	M__index__() (Int, error)
}

object.__index__(self)

type I__init__

type I__init__ interface {
	M__init__(self, args, kwargs Object) (Object, error)
}

Called when the instance is created. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: BaseClass.__init__(self, [args...]). As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime. object.__init__(self[, ...])

type I__instancecheck__

type I__instancecheck__ interface {
	M__instancecheck__(instance Object) (Object, error)
}

Return true if instance should be considered a (direct or indirect) instance of class. If defined, called to implement isinstance(instance, class). object.__instancecheck__(self, instance)

type I__int__

type I__int__ interface {
	M__int__() (Object, error)
}

object.__int__(self)

type I__invert__

type I__invert__ interface {
	M__invert__() (Object, error)
}

object.__invert__(self)

type I__ior__

type I__ior__ interface {
	M__ior__(other Object) (Object, error)
}

object.__ior__(self, other)

type I__ipow__

type I__ipow__ interface {
	M__ipow__(other, modulo Object) (Object, error)
}

type I__irshift__

type I__irshift__ interface {
	M__irshift__(other Object) (Object, error)
}

object.__irshift__(self, other)

type I__isub__

type I__isub__ interface {
	M__isub__(other Object) (Object, error)
}

object.__isub__(self, other)

type I__iter__

type I__iter__ interface {
	M__iter__() (Object, error)
}

This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container, and should also be made available as the method keys().

Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see Iterator Types. object.__iter__(self)

type I__itruediv__

type I__itruediv__ interface {
	M__itruediv__(other Object) (Object, error)
}

object.__itruediv__(self, other)

type I__ixor__

type I__ixor__ interface {
	M__ixor__(other Object) (Object, error)
}

object.__ixor__(self, other)

type I__le__

type I__le__ interface {
	M__le__(other Object) (Object, error)
}

object.__le__(self, other)

type I__len__

type I__len__ interface {
	M__len__() (Object, error)
}

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context. object.__len__(self)

type I__length_hint__

type I__length_hint__ interface {
	M__length_hint__() (Object, error)
}

Called to implement operator.length_hint(). Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer >= 0. This method is purely an optimization and is never required for correctness.

New in version 3.4. object.__length_hint__(self)

type I__lshift__

type I__lshift__ interface {
	M__lshift__(other Object) (Object, error)
}

object.__lshift__(self, other)

type I__lt__

type I__lt__ interface {
	M__lt__(other Object) (Object, error)
}

These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: x<y calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).

A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments. By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected. See the paragraph on __hash__() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys.

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection.

Arguments to rich comparison methods are never coerced.

To automatically generate ordering operations from a single root operation, see functools.total_ordering(). object.__lt__(self, other)

type I__mod__

type I__mod__ interface {
	M__mod__(other Object) (Object, error)
}

object.__mod__(self, other)

type I__mul__

type I__mul__ interface {
	M__mul__(other Object) (Object, error)
}

object.__mul__(self, other)

type I__ne__

type I__ne__ interface {
	M__ne__(other Object) (Object, error)
}

object.__ne__(self, other)

type I__neg__

type I__neg__ interface {
	M__neg__() (Object, error)
}

object.__neg__(self)

type I__new__

type I__new__ interface {
	M__new__(cls, args, kwargs Object) (Object, error)
}

Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).

Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation. object.__new__(cls[, ...])

type I__next__

type I__next__ interface {
	M__next__() (Object, error)
}

The next method for iterators

type I__or__

type I__or__ interface {
	M__or__(other Object) (Object, error)
}

object.__or__(self, other)

type I__pos__

type I__pos__ interface {
	M__pos__() (Object, error)
}

object.__pos__(self)

type I__pow__

type I__pow__ interface {
	M__pow__(other, modulo Object) (Object, error)
}

object.__pow__(self, other[, modulo])

type I__radd__

type I__radd__ interface {
	M__radd__(other Object) (Object, error)
}

object.__radd__(self, other)

type I__rand__

type I__rand__ interface {
	M__rand__(other Object) (Object, error)
}

object.__rand__(self, other)

type I__rdivmod__

type I__rdivmod__ interface {
	M__rdivmod__(other Object) (Object, Object, error)
}

object.__rdivmod__(self, other)

type I__repr__

type I__repr__ interface {
	M__repr__() (Object, error)
}

Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. object.__repr__(self)

type I__reversed__

type I__reversed__ interface {
	M__reversed__() (Object, error)
}

Called (if present) by the reversed() built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order.

If the __reversed__() method is not provided, the reversed() built-in will fall back to using the sequence protocol (__len__() and __getitem__()). Objects that support the sequence protocol should only provide __reversed__() if they can provide an implementation that is more efficient than the one provided by reversed(). object.__reversed__(self)

type I__rfloordiv__

type I__rfloordiv__ interface {
	M__rfloordiv__(other Object) (Object, error)
}

object.__rfloordiv__(self, other)

type I__rlshift__

type I__rlshift__ interface {
	M__rlshift__(other Object) (Object, error)
}

object.__rlshift__(self, other)

type I__rmod__

type I__rmod__ interface {
	M__rmod__(other Object) (Object, error)
}

object.__rmod__(self, other)

type I__rmul__

type I__rmul__ interface {
	M__rmul__(other Object) (Object, error)
}

object.__rmul__(self, other)

type I__ror__

type I__ror__ interface {
	M__ror__(other Object) (Object, error)
}

object.__ror__(self, other)

type I__round__

type I__round__ interface {
	M__round__(n Object) (Object, error)
}

object.__round__(self, n)

type I__rpow__

type I__rpow__ interface {
	M__rpow__(other Object) (Object, error)
}

object.__rpow__(self, other)

type I__rrshift__

type I__rrshift__ interface {
	M__rrshift__(other Object) (Object, error)
}

object.__rrshift__(self, other)

type I__rshift__

type I__rshift__ interface {
	M__rshift__(other Object) (Object, error)
}

object.__rshift__(self, other)

type I__rsub__

type I__rsub__ interface {
	M__rsub__(other Object) (Object, error)
}

object.__rsub__(self, other)

type I__rtruediv__

type I__rtruediv__ interface {
	M__rtruediv__(other Object) (Object, error)
}

object.__rtruediv__(self, other)

type I__rxor__

type I__rxor__ interface {
	M__rxor__(other Object) (Object, error)
}

object.__rxor__(self, other)

type I__set__

type I__set__ interface {
	M__set__(instance, value Object) (Object, error)
}

Called to set the attribute on an instance of the owner class to a new value. object.__set__(self, instance, value)

type I__setattr__

type I__setattr__ interface {
	M__setattr__(name string, value Object) (Object, error)
}

Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). name is the attribute name, value is the value to be assigned to it.

If __setattr__() wants to assign to an instance attribute, it should call the base class method with the same name, for example, object.__setattr__(self, name, value). object.__setattr__(self, name, value)

type I__setitem__

type I__setitem__ interface {
	M__setitem__(key, value Object) (Object, error)
}

Called to implement assignment to self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. The same exceptions should be raised for improper key values as for the __getitem__() method. object.__setitem__(self, key, value)

type I__str__

type I__str__ interface {
	M__str__() (Object, error)
}

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

The default implementation defined by the built-in type object calls object.__repr__(). object.__str__(self)

type I__sub__

type I__sub__ interface {
	M__sub__(other Object) (Object, error)
}

object.__sub__(self, other)

type I__subclasscheck__

type I__subclasscheck__ interface {
	M__subclasscheck__(subclass Object) (Object, error)
}

Return true if subclass should be considered a (direct or indirect) subclass of class. If defined, called to implement issubclass(subclass, class). object.__subclasscheck__(self, subclass)

type I__truediv__

type I__truediv__ interface {
	M__truediv__(other Object) (Object, error)
}

object.__truediv__(self, other)

type I__trunc__

type I__trunc__ interface {
	M__trunc__() (Object, error)
}

Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__().

type I__xor__

type I__xor__ interface {
	M__xor__(other Object) (Object, error)
}

object.__xor__(self, other)

type I_close

type I_close interface {
	Close() (Object, error)
}

type I_generator

type I_generator interface {
	I_iterator
	I_send
	I_throw
	I_close
}

Interface all generators must satisfy

type I_iterator

type I_iterator interface {
	I__iter__
	I__next__
}

Interface all iterators must satisfy

type I_send

type I_send interface {
	Send(value Object) (Object, error)
}

Generator interfaces

type I_throw

type I_throw interface {
	Throw(args Tuple, kwargs StringDict) (Object, error)
}

type InitFunc

type InitFunc func(self Object, args Tuple, kwargs StringDict) error

type Int

type Int int64

func GetInt added in v0.1.0

func GetInt(obj Object) (Int, error)

GetInt is a high-level convenience function that converts the given value to an int.

func GetLen added in v0.1.0

func GetLen(obj Object) (Int, error)

GetLen is a high-level convenience function that returns the length of the given Object.

func Index

func Index(a Object) (Int, error)

Index the python Object returning an Int

Will raise TypeError if Index can't be run on this object

func (Int) GoInt

func (x Int) GoInt() (int, error)

Truncates to go int

If it is outside the range of an go int it will return an error

func (Int) GoInt64

func (x Int) GoInt64() (int64, error)

Truncates to go int64

If it is outside the range of an go int64 it will return an error

func (Int) M__abs__

func (a Int) M__abs__() (Object, error)

func (Int) M__add__

func (a Int) M__add__(other Object) (Object, error)

func (Int) M__and__

func (a Int) M__and__(other Object) (Object, error)

func (Int) M__bool__

func (a Int) M__bool__() (Object, error)

func (Int) M__ceil__

func (a Int) M__ceil__() (Object, error)

func (Int) M__complex__

func (a Int) M__complex__() (Object, error)

func (Int) M__divmod__

func (a Int) M__divmod__(other Object) (Object, Object, error)

func (Int) M__eq__

func (a Int) M__eq__(other Object) (Object, error)

func (Int) M__float__

func (a Int) M__float__() (Object, error)

func (Int) M__floor__

func (a Int) M__floor__() (Object, error)

func (Int) M__floordiv__

func (a Int) M__floordiv__(other Object) (Object, error)

func (Int) M__ge__

func (a Int) M__ge__(other Object) (Object, error)

func (Int) M__gt__

func (a Int) M__gt__(other Object) (Object, error)

func (Int) M__iadd__

func (a Int) M__iadd__(other Object) (Object, error)

func (Int) M__iand__

func (a Int) M__iand__(other Object) (Object, error)

func (Int) M__ifloordiv__

func (a Int) M__ifloordiv__(other Object) (Object, error)

func (Int) M__ilshift__

func (a Int) M__ilshift__(other Object) (Object, error)

func (Int) M__imod__

func (a Int) M__imod__(other Object) (Object, error)

func (Int) M__imul__

func (a Int) M__imul__(other Object) (Object, error)

func (Int) M__index__

func (a Int) M__index__() (Int, error)

func (Int) M__int__

func (a Int) M__int__() (Object, error)

func (Int) M__invert__

func (a Int) M__invert__() (Object, error)

func (Int) M__ior__

func (a Int) M__ior__(other Object) (Object, error)

func (Int) M__ipow__

func (a Int) M__ipow__(other, modulus Object) (Object, error)

func (Int) M__irshift__

func (a Int) M__irshift__(other Object) (Object, error)

func (Int) M__isub__

func (a Int) M__isub__(other Object) (Object, error)

func (Int) M__itruediv__

func (a Int) M__itruediv__(other Object) (Object, error)

func (Int) M__ixor__

func (a Int) M__ixor__(other Object) (Object, error)

func (Int) M__le__

func (a Int) M__le__(other Object) (Object, error)

func (Int) M__lshift__

func (a Int) M__lshift__(other Object) (Object, error)

func (Int) M__lt__

func (a Int) M__lt__(other Object) (Object, error)

func (Int) M__mod__

func (a Int) M__mod__(other Object) (Object, error)

func (Int) M__mul__

func (a Int) M__mul__(other Object) (Object, error)

func (Int) M__ne__

func (a Int) M__ne__(other Object) (Object, error)

func (Int) M__neg__

func (a Int) M__neg__() (Object, error)

func (Int) M__or__

func (a Int) M__or__(other Object) (Object, error)

func (Int) M__pos__

func (a Int) M__pos__() (Object, error)

func (Int) M__pow__

func (a Int) M__pow__(other, modulus Object) (Object, error)

func (Int) M__radd__

func (a Int) M__radd__(other Object) (Object, error)

func (Int) M__rand__

func (a Int) M__rand__(other Object) (Object, error)

func (Int) M__rdivmod__

func (a Int) M__rdivmod__(other Object) (Object, Object, error)

func (Int) M__repr__

func (a Int) M__repr__() (Object, error)

func (Int) M__rfloordiv__

func (a Int) M__rfloordiv__(other Object) (Object, error)

func (Int) M__rlshift__

func (a Int) M__rlshift__(other Object) (Object, error)

func (Int) M__rmod__

func (a Int) M__rmod__(other Object) (Object, error)

func (Int) M__rmul__

func (a Int) M__rmul__(other Object) (Object, error)

func (Int) M__ror__

func (a Int) M__ror__(other Object) (Object, error)

func (Int) M__round__

func (a Int) M__round__(digits Object) (Object, error)

func (Int) M__rpow__

func (a Int) M__rpow__(other Object) (Object, error)

func (Int) M__rrshift__

func (a Int) M__rrshift__(other Object) (Object, error)

func (Int) M__rshift__

func (a Int) M__rshift__(other Object) (Object, error)

func (Int) M__rsub__

func (a Int) M__rsub__(other Object) (Object, error)

func (Int) M__rtruediv__

func (a Int) M__rtruediv__(other Object) (Object, error)

func (Int) M__rxor__

func (a Int) M__rxor__(other Object) (Object, error)

func (Int) M__str__

func (a Int) M__str__() (Object, error)

func (Int) M__sub__

func (a Int) M__sub__(other Object) (Object, error)

func (Int) M__truediv__

func (a Int) M__truediv__(other Object) (Object, error)

func (Int) M__trunc__

func (a Int) M__trunc__() (Object, error)

func (Int) M__xor__

func (a Int) M__xor__(other Object) (Object, error)

func (Int) Type

func (o Int) Type() *Type

Type of this Int object

type InternalMethod

type InternalMethod int

Internal method types implemented within eval.go

const (
	InternalMethodNone InternalMethod = iota
	InternalMethodGlobals
	InternalMethodLocals
	InternalMethodImport
	InternalMethodEval
	InternalMethodExec
)

type Iterator

type Iterator struct {
	Pos int
	Seq Object
}

A python Iterator object

func NewIterator

func NewIterator(Seq Object) *Iterator

Define a new iterator

func (*Iterator) M__iter__

func (it *Iterator) M__iter__() (Object, error)

func (*Iterator) M__next__

func (it *Iterator) M__next__() (res Object, err error)

Get next one from the iteration

func (*Iterator) Type

func (o *Iterator) Type() *Type

Type of this object

type List

type List struct {
	Items []Object
}

FIXME lists are mutable so this should probably be struct { Tuple } then can use the sub methods on Tuple

func NewList

func NewList() *List

Make a new empty list

func NewListFromItems

func NewListFromItems(items []Object) *List

Make a new list from an []Object

The []Object is copied into the list

func NewListFromStrings added in v0.1.0

func NewListFromStrings(items []string) *List

Makes an argv into a tuple

func NewListSized

func NewListSized(n int) *List

Make a list with n nil elements

func NewListWithCapacity

func NewListWithCapacity(n int) *List

Make a new empty list with given capacity

func SequenceList

func SequenceList(v Object) (*List, error)

Converts a sequence object v into a List

func (*List) Append

func (l *List) Append(item Object)

Append an item

func (*List) Copy

func (l *List) Copy() *List

Copy a list object

func (*List) DelItem

func (a *List) DelItem(i int)

Removes the item at i

func (*List) Extend

func (l *List) Extend(items []Object)

Extend the list with items

func (*List) ExtendSequence

func (l *List) ExtendSequence(seq Object) error

Extends the list with the sequence passed in

func (*List) ExtendWithStrings added in v0.1.0

func (l *List) ExtendWithStrings(items []string)

Extend the list with strings

func (*List) Len

func (l *List) Len() int

Len of list

func (*List) M__add__

func (a *List) M__add__(other Object) (Object, error)

func (*List) M__bool__

func (l *List) M__bool__() (Object, error)

func (*List) M__delitem__

func (a *List) M__delitem__(key Object) (Object, error)

Removes items from a list

func (*List) M__eq__

func (a *List) M__eq__(other Object) (Object, error)

func (*List) M__getitem__

func (l *List) M__getitem__(key Object) (Object, error)

func (*List) M__iadd__

func (a *List) M__iadd__(other Object) (Object, error)

func (*List) M__imul__

func (a *List) M__imul__(other Object) (Object, error)

func (*List) M__iter__

func (l *List) M__iter__() (Object, error)

func (*List) M__len__

func (l *List) M__len__() (Object, error)

func (*List) M__mul__

func (l *List) M__mul__(other Object) (Object, error)

func (*List) M__ne__

func (a *List) M__ne__(other Object) (Object, error)

func (*List) M__radd__

func (a *List) M__radd__(other Object) (Object, error)

func (*List) M__repr__

func (l *List) M__repr__() (Object, error)

func (*List) M__rmul__

func (a *List) M__rmul__(other Object) (Object, error)

func (*List) M__setitem__

func (l *List) M__setitem__(key, value Object) (Object, error)

func (*List) M__str__

func (l *List) M__str__() (Object, error)

func (*List) Resize

func (l *List) Resize(newSize int)

Resize the list

func (*List) Type

func (o *List) Type() *Type

Type of this List object

type Map added in v0.2.0

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

A python Map object

func (*Map) M__iter__ added in v0.2.0

func (m *Map) M__iter__() (Object, error)

func (*Map) M__next__ added in v0.2.0

func (m *Map) M__next__() (Object, error)

func (*Map) Type added in v0.2.0

func (m *Map) Type() *Type

Type of this object

type Method

type Method struct {
	// Name of this function
	Name string
	// Doc string
	Doc string
	// Flags - see METH_* flags
	Flags int

	// Parent module of this method
	Module *Module
	// contains filtered or unexported fields
}

A python Method object

func MustNewMethod

func MustNewMethod(name string, method interface{}, flags int, doc string) *Method

As NewMethod but panics on error

func NewMethod

func NewMethod(name string, method interface{}, flags int, doc string) (*Method, error)

Define a new method

func (*Method) Call

func (m *Method) Call(self Object, args Tuple) (Object, error)

Call the method with the given arguments

func (*Method) CallWithKeywords

func (m *Method) CallWithKeywords(self Object, args Tuple, kwargs StringDict) (Object, error)

Call the method with the given arguments

func (*Method) Internal

func (m *Method) Internal() InternalMethod

Returns the InternalMethod type of this method

func (*Method) M__call__

func (m *Method) M__call__(args Tuple, kwargs StringDict) (Object, error)

Call a method

func (*Method) M__eq__

func (m *Method) M__eq__(other Object) (Object, error)

FIXME this should be the default?

func (*Method) M__get__

func (m *Method) M__get__(instance, owner Object) (Object, error)

Read a method from a class which makes a bound method

func (*Method) M__ne__

func (m *Method) M__ne__(other Object) (Object, error)

FIXME this should be the default?

func (*Method) Type

func (o *Method) Type() *Type

Type of this object

type Module

type Module struct {
	ModuleImpl *ModuleImpl // Parent implementation of this Module instance
	Globals    StringDict  // Initialized from ModuleImpl.Globals
	Context    Context     // Parent context that "owns" this Module instance
}

Module is a runtime instance of a ModuleImpl bound to the py.Context that imported it.

func RunCode added in v0.1.0

func RunCode(ctx Context, code *Code, codeDesc string, inModule interface{}) (*Module, error)

RunCode executes the given code object within the given module and returns the Module to indicate success.

If inModule is a *Module, then the code is run in that module.

If inModule is nil, the code is run in a new __main__ module (and the new Module is returned).

If inModule is a string, the code is run in a new module with the given name (and the new Module is returned).

func RunFile added in v0.1.0

func RunFile(ctx Context, pathname string, opts CompileOpts, inModule interface{}) (*Module, error)

RunFile resolves the given pathname, compiles as needed, executes the code in the given module, and returns the Module to indicate success.

See RunCode() for description of inModule.

func RunSrc added in v0.1.0

func RunSrc(ctx Context, pySrc string, pySrcDesc string, inModule interface{}) (*Module, error)

RunSrc compiles the given python buffer and executes it within the given module and returns the Module to indicate success.

See RunCode() for description of inModule.

func (*Module) Call

func (m *Module) Call(name string, args Tuple, kwargs StringDict) (Object, error)

Calls a named method of a module

func (*Module) GetDict

func (m *Module) GetDict() StringDict

Get the Dict

func (*Module) M__repr__

func (m *Module) M__repr__() (Object, error)

func (*Module) Type

func (o *Module) Type() *Type

Type of this object

type ModuleFlags added in v0.1.0

type ModuleFlags int32
const (
	// ShareModule signals that an embedded module is threadsafe and read-only, meaninging it could be shared across multiple py.Context instances (for efficiency).
	// Otherwise, ModuleImpl will create a separate py.Module instance for each py.Context that imports it.
	// This should be used with extreme caution since any module mutation (write) means possible cross-context data corruption.
	ShareModule ModuleFlags = 0x01

	MainModuleName = "__main__"
)

type ModuleImpl added in v0.1.0

type ModuleImpl struct {
	Info            ModuleInfo
	Methods         []*Method     // Module-bound global method functions
	Globals         StringDict    // Module-bound global variables
	CodeSrc         string        // Module code body (source code to be compiled)
	CodeBuf         []byte        // Module code body (serialized py.Code object)
	Code            *Code         // Module code body
	OnContextClosed func(*Module) // Callback for when a py.Context is closing to release resources
}

ModuleImpl is used for modules that are ready to be imported into a py.Context. The model is that a ModuleImpl is read-only and instantiates a Module into a py.Context when imported.

By convention, .Code is executed when a module instance is initialized. If nil, then .CodeBuf or .CodeSrc will be auto-compiled to set .Code.

func GetModuleImpl added in v0.1.0

func GetModuleImpl(moduleName string) *ModuleImpl

type ModuleInfo added in v0.1.0

type ModuleInfo struct {
	Name     string // __name__ (if nil, "__main__" is used)
	Doc      string // __doc__
	FileDesc string // __file__
	Flags    ModuleFlags
}

ModuleInfo contains info and about a module and can specify flags that affect how it is imported into a py.Context

type ModuleStore added in v0.1.0

type ModuleStore struct {

	// Builtin module
	Builtins *Module
	// this should be the frozen module importlib/_bootstrap.py generated
	// by Modules/_freeze_importlib.c into Python/importlib.h
	Importlib *Module
	// contains filtered or unexported fields
}

ModuleStore is a container of Module imported into an owning py.Context.

func NewModuleStore added in v0.1.0

func NewModuleStore() *ModuleStore

func (*ModuleStore) GetModule added in v0.1.0

func (store *ModuleStore) GetModule(name string) (*Module, error)

Gets a module

func (*ModuleStore) MustGetModule added in v0.1.0

func (store *ModuleStore) MustGetModule(name string) *Module

Gets a module or panics

func (*ModuleStore) NewModule added in v0.1.0

func (store *ModuleStore) NewModule(ctx Context, impl *ModuleImpl) (*Module, error)

NewModule adds a new Module instance to this ModuleStore. Each given Method prototype is used to create a new "live" Method bound this the newly created Module. This func also sets appropriate module global attribs based on the given ModuleInfo (e.g. __name__).

func (*ModuleStore) OnContextClosed added in v0.1.0

func (store *ModuleStore) OnContextClosed()

OnContextClosed signals all module instances that the parent py.Context has closed

type NewFunc

type NewFunc func(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

type NoneType

type NoneType struct{}

func (NoneType) M__bool__

func (a NoneType) M__bool__() (Object, error)

func (NoneType) M__eq__

func (a NoneType) M__eq__(other Object) (Object, error)

func (NoneType) M__ne__

func (a NoneType) M__ne__(other Object) (Object, error)

func (NoneType) M__repr__

func (a NoneType) M__repr__() (Object, error)

func (NoneType) M__str__

func (a NoneType) M__str__() (Object, error)

func (NoneType) Type

func (s NoneType) Type() *Type

Type of this object

type Object

type Object interface {
	Type() *Type
}

A python object

func Abs

func Abs(a Object) (Object, error)

Abs the python Object returning an Object

Will raise TypeError if Abs can't be run on this object

func Add

func Add(a, b Object) (Object, error)

Add two python objects together returning an Object

Will raise TypeError if can't be add can't be run on these objects

func And

func And(a, b Object) (Object, error)

And two python objects together returning an Object

Will raise TypeError if can't be and can't be run on these objects

func BuiltinImport

func BuiltinImport(ctx Context, self Object, args Tuple, kwargs StringDict, currentGlobal StringDict) (Object, error)

The actual import code

func BytesNew

func BytesNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)

BytesNew

func Call

func Call(fn Object, args Tuple, kwargs StringDict) (Object, error)

Calls function fnObj with args and kwargs in a new vm (or directly if Go code)

kwargs should be nil if not required

fnObj must be a callable type such as *py.Method or *py.Function

The result is returned

func ClassMethodNew

func ClassMethodNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)

ClassMethodNew

func ComplexNew

func ComplexNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

ComplexNew

func DelItem

func DelItem(self Object, key Object) (Object, error)

Delitem

func DictNew added in v0.2.0

func DictNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

DictNew

func EnumerateNew added in v0.1.0

func EnumerateNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

EnumerateTypeNew

func Eq

func Eq(a Object, b Object) (Object, error)

Eq two python objects returning a boolean result

Will raise TypeError if Eq can't be run on this object

func ExceptionNew

func ExceptionNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

ExceptionNew

func FilterTypeNew added in v0.2.0

func FilterTypeNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)

FilterTypeNew

func FloatFromString

func FloatFromString(str string) (Object, error)

FloatFromString turns a string into a Float

func FloatNew

func FloatNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

FloatNew

func FloorDiv

func FloorDiv(a, b Object) (Object, error)

FloorDiv two python objects together returning an Object

Will raise TypeError if can't be floordiv can't be run on these objects

func Ge

func Ge(a Object, b Object) (Object, error)

Ge two python objects returning a boolean result

Will raise TypeError if Ge can't be run on this object

func GetAttr

func GetAttr(self Object, keyObj Object) (res Object, err error)

GetAttrErr - returns the result or an err to be raised if not found

If not found an AttributeError will be returned

func GetAttrString

func GetAttrString(self Object, key string) (res Object, err error)

GetAttrString - returns the result or an err to be raised if not found

If not found err will be an AttributeError

func GetItem

func GetItem(self Object, key Object) (Object, error)

GetItem

func Gt

func Gt(a Object, b Object) (Object, error)

Gt two python objects returning a boolean result

Will raise TypeError if Gt can't be run on this object

func IAdd

func IAdd(a, b Object) (Object, error)

Inplace add

func IAnd

func IAnd(a, b Object) (Object, error)

Inplace and

func IFloorDiv

func IFloorDiv(a, b Object) (Object, error)

Inplace floordiv

func ILshift

func ILshift(a, b Object) (Object, error)

Inplace lshift

func IMod

func IMod(a, b Object) (Object, error)

Inplace mod

func IMul

func IMul(a, b Object) (Object, error)

Inplace mul

func IOr

func IOr(a, b Object) (Object, error)

Inplace or

func IPow

func IPow(a, b, c Object) (Object, error)

Inplace pow

func IRshift

func IRshift(a, b Object) (Object, error)

Inplace rshift

func ISub

func ISub(a, b Object) (Object, error)

Inplace sub

func ITrueDiv

func ITrueDiv(a, b Object) (Object, error)

Inplace truediv

func IXor

func IXor(a, b Object) (Object, error)

Inplace xor

func ImportModuleLevelObject

func ImportModuleLevelObject(ctx Context, name string, globals, locals StringDict, fromlist Tuple, level int) (Object, error)

The workings of __import__

__import__(name, globals=None, locals=None, fromlist=(), level=0)

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement import spam results in bytecode resembling the following code:

spam = __import__('spam', globals(), locals(), [], 0) The statement import spam.ham results in this call:

spam = __import__('spam.ham', globals(), locals(), [], 0)

Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage

Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

Changed in version 3.3: Negative values for level are no longer supported (which also changes the default value to 0).

func IntFromString

func IntFromString(str string, base int) (Object, error)

Create an Int (or BigInt) from the string passed in

FIXME check this is 100% python compatible

func IntNew

func IntNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

IntNew

func Invert

func Invert(a Object) (Object, error)

Invert the python Object returning an Object

Will raise TypeError if Invert can't be run on this object

func Iter

func Iter(self Object) (res Object, err error)

Returns an iterator object

Call __Iter__ Returns an iterator object

If object is sequence object, create an iterator

func Le

func Le(a Object, b Object) (Object, error)

Le two python objects returning a boolean result

Will raise TypeError if Le can't be run on this object

func Len

func Len(self Object) (Object, error)

Returns the number of items of a sequence or mapping

func ListNew

func ListNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)

ListNew

func Lshift

func Lshift(a, b Object) (Object, error)

Lshift two python objects together returning an Object

Will raise TypeError if can't be lshift can't be run on these objects

func Lt

func Lt(a Object, b Object) (Object, error)

Lt two python objects returning a boolean result

Will raise TypeError if Lt can't be run on this object

func MakeBool

func MakeBool(a Object) (Object, error)

Bool is called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

func MakeComplex

func MakeComplex(a Object) (Object, error)

MakeComplex the python Object returning an Object

Will raise TypeError if MakeComplex can't be run on this object

func MakeFloat

func MakeFloat(a Object) (Object, error)

MakeFloat the python Object returning an Object

Will raise TypeError if MakeFloat can't be run on this object

func MakeInt

func MakeInt(a Object) (Object, error)

MakeInt the python Object returning an Object

Will raise TypeError if MakeInt can't be run on this object

func MapTypeNew added in v0.2.0

func MapTypeNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)

MapType

func Mod

func Mod(a, b Object) (Object, error)

Mod two python objects together returning an Object

Will raise TypeError if can't be mod can't be run on these objects

func Mul

func Mul(a, b Object) (Object, error)

Mul two python objects together returning an Object

Will raise TypeError if can't be mul can't be run on these objects

func Ne

func Ne(a Object, b Object) (Object, error)

Ne two python objects returning a boolean result

Will raise TypeError if Ne can't be run on this object

func Neg

func Neg(a Object) (Object, error)

Neg the python Object returning an Object

Will raise TypeError if Neg can't be run on this object

func Next

func Next(self Object) (obj Object, err error)

Call __next__ for the python object

Returns the next object

err == StopIteration or subclass when finished

func Not

func Not(a Object) (Object, error)

Return the result of not a

func ObjectGetAttr

func ObjectGetAttr(o Object, attr string) Object

Gets the attribute attr from object or returns nil

func ObjectNew

func ObjectNew(t *Type, args Tuple, kwargs StringDict) (Object, error)

func ObjectRepr

func ObjectRepr(o Object) Object

Gets the repr for an object

func OpenFile added in v0.0.3

func OpenFile(filename, mode string, buffering int) (Object, error)

func Or

func Or(a, b Object) (Object, error)

Or two python objects together returning an Object

Will raise TypeError if can't be or can't be run on these objects

func Pos

func Pos(a Object) (Object, error)

Pos the python Object returning an Object

Will raise TypeError if Pos can't be run on this object

func Pow

func Pow(a, b, c Object) (Object, error)

Pow three python objects together returning an Object

If c != None then it won't attempt to call __rpow__

Will raise TypeError if can't be pow can't be run on these objects

func RangeNew

func RangeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

RangeNew

func Repr

func Repr(self Object) (Object, error)

Calls __str__ on the object

Calls __repr__ on the object or returns a sensible default

func Rshift

func Rshift(a, b Object) (Object, error)

Rshift two python objects together returning an Object

Will raise TypeError if can't be rshift can't be run on these objects

func Send

func Send(self, value Object) (Object, error)

Call send for the python object

func SetAttr

func SetAttr(self Object, keyObj Object, value Object) (Object, error)

SetAttr

func SetAttrString

func SetAttrString(self Object, key string, value Object) (Object, error)

SetAttrString

func SetItem

func SetItem(self Object, key Object, value Object) (Object, error)

SetItem

func SetNew

func SetNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

SetNew

func SliceNew

func SliceNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

SliceNew

func StaticMethodNew

func StaticMethodNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)

StaticMethodNew

func Str

func Str(self Object) (Object, error)

Calls __str__ on the object and if not found calls __repr__

func StrNew

func StrNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

StrNew

func Sub

func Sub(a, b Object) (Object, error)

Sub two python objects together returning an Object

Will raise TypeError if can't be sub can't be run on these objects

func TrueDiv

func TrueDiv(a, b Object) (Object, error)

TrueDiv two python objects together returning an Object

Will raise TypeError if can't be truediv can't be run on these objects

func TupleNew

func TupleNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)

TupleNew

func TypeCall

func TypeCall(self Object, name string, args Tuple, kwargs StringDict) (Object, bool, error)

Calls a type method on obj

If obj isnt a *Type or the method isn't found on it returns (nil, false, nil)

Otherwise returns (object, true, err)

May raise exceptions if calling the method fails

func TypeCall0

func TypeCall0(self Object, name string) (Object, bool, error)

Calls TypeCall with 0 arguments

func TypeCall1

func TypeCall1(self Object, name string, arg Object) (Object, bool, error)

Calls TypeCall with 1 argument

func TypeCall2

func TypeCall2(self Object, name string, arg1, arg2 Object) (Object, bool, error)

Calls TypeCall with 2 arguments

func TypeNew

func TypeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

Create a new type

func XImportModuleLevelObject

func XImportModuleLevelObject(ctx Context, nameObj, given_globals, locals, given_fromlist Object, level int) (Object, error)

Straight port of the python code

This calls functins from _bootstrap.py which is a frozen module

Too much functionality for the moment

func Xor

func Xor(a, b Object) (Object, error)

Xor two python objects together returning an Object

Will raise TypeError if can't be xor can't be run on these objects

func ZipTypeNew added in v0.1.0

func ZipTypeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)

ZipTypeNew

type Property

type Property struct {
	Fget func(self Object) (Object, error)
	Fset func(self, value Object) error
	Fdel func(self Object) error
	Doc  string
}

A python Property object

func (*Property) M__delete__

func (p *Property) M__delete__(instance Object) (Object, error)

func (*Property) M__get__

func (p *Property) M__get__(instance, owner Object) (Object, error)

func (*Property) M__set__

func (p *Property) M__set__(instance, value Object) (Object, error)

func (*Property) Type

func (o *Property) Type() *Type

Type of this object

type PyCFunction

type PyCFunction func(self Object, args Tuple) (Object, error)

Called with self and a tuple of args

type PyCFunction1Arg

type PyCFunction1Arg func(Object, Object) (Object, error)

Called with one (unnamed) parameter only

type PyCFunctionNoArgs

type PyCFunctionNoArgs func(Object) (Object, error)

Called with self only

type PyCFunctionWithKeywords

type PyCFunctionWithKeywords func(self Object, args Tuple, kwargs StringDict) (Object, error)

Called with self, a tuple of args and a stringdic of kwargs

type Range

type Range struct {
	Start  Int
	Stop   Int
	Step   Int
	Length Int
}

A python Range object FIXME one day support BigInts too!

func (*Range) M__eq__ added in v0.1.0

func (a *Range) M__eq__(other Object) (Object, error)

func (*Range) M__getitem__ added in v0.1.0

func (r *Range) M__getitem__(key Object) (Object, error)

func (*Range) M__iter__

func (r *Range) M__iter__() (Object, error)

Make a range iterator from a range

func (*Range) M__len__ added in v0.1.0

func (r *Range) M__len__() (Object, error)

func (*Range) M__ne__ added in v0.1.0

func (a *Range) M__ne__(other Object) (Object, error)

func (*Range) M__repr__ added in v0.1.0

func (r *Range) M__repr__() (Object, error)

func (*Range) M__str__ added in v0.1.0

func (r *Range) M__str__() (Object, error)

func (*Range) Type

func (o *Range) Type() *Type

Type of this object

type RangeIterator

type RangeIterator struct {
	Range
	Index Int
}

A python Range iterator

func (*RangeIterator) M__iter__

func (it *RangeIterator) M__iter__() (Object, error)

Range iterator

func (*RangeIterator) M__next__

func (it *RangeIterator) M__next__() (Object, error)

Range iterator next

func (*RangeIterator) Type

func (o *RangeIterator) Type() *Type

Type of this object

type Runtime added in v0.1.0

type Runtime struct {
	ModuleImpls map[string]*ModuleImpl
	// contains filtered or unexported fields
}

func (*Runtime) RegisterModule added in v0.1.0

func (rt *Runtime) RegisterModule(impl *ModuleImpl)

type Set

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

func NewSet

func NewSet() *Set

Make a new empty set

func NewSetFromItems

func NewSetFromItems(items []Object) *Set

Make a new set with the items passed in

func NewSetWithCapacity

func NewSetWithCapacity(n int) *Set

Make a new empty set with capacity for n items

func SequenceSet added in v0.1.0

func SequenceSet(v Object) (*Set, error)

Converts a sequence object v into a Set

func (*Set) Add

func (s *Set) Add(item Object)

Add an item to the set

func (*Set) M__and__ added in v0.1.0

func (s *Set) M__and__(other Object) (Object, error)

func (*Set) M__bool__

func (s *Set) M__bool__() (Object, error)

func (*Set) M__eq__

func (a *Set) M__eq__(other Object) (Object, error)

func (*Set) M__iter__

func (s *Set) M__iter__() (Object, error)

func (*Set) M__len__

func (s *Set) M__len__() (Object, error)

func (*Set) M__ne__

func (a *Set) M__ne__(other Object) (Object, error)

func (*Set) M__or__ added in v0.1.0

func (s *Set) M__or__(other Object) (Object, error)

func (*Set) M__repr__ added in v0.1.0

func (s *Set) M__repr__() (Object, error)

func (*Set) M__sub__ added in v0.1.0

func (s *Set) M__sub__(other Object) (Object, error)

func (*Set) M__xor__ added in v0.1.0

func (s *Set) M__xor__(other Object) (Object, error)

func (*Set) Type

func (o *Set) Type() *Type

Type of this Set object

func (*Set) Update

func (s *Set) Update(items []Object)

Extend the set with items

type SetValue

type SetValue struct{}

type Slice

type Slice struct {
	Start Object
	Stop  Object
	Step  Object
}

A python Slice object

func NewSlice

func NewSlice(start, stop, step Object) *Slice

Make a new slice object

func (*Slice) GetIndices

func (r *Slice) GetIndices(length int) (start, stop, step, slicelength int, err error)

GetIndices

Retrieve the start, stop, and step indices from the slice object slice assuming a sequence of length length, and store the length of the slice in slicelength. Out of bounds indices are clipped in a manner consistent with the handling of normal slices.

func (*Slice) M__eq__ added in v0.1.0

func (a *Slice) M__eq__(other Object) (Object, error)

func (*Slice) M__ne__ added in v0.1.0

func (a *Slice) M__ne__(other Object) (Object, error)

func (*Slice) Type

func (o *Slice) Type() *Type

Type of this object

type StaticMethod

type StaticMethod struct {
	Callable Object
	Dict     StringDict
}

func (*StaticMethod) GetDict

func (c *StaticMethod) GetDict() StringDict

Get the Dict

func (*StaticMethod) M__get__

func (c *StaticMethod) M__get__(instance, owner Object) (Object, error)

Read a staticmethod from a class - no bound method here

func (StaticMethod) Type

func (o StaticMethod) Type() *Type

Type of this StaticMethod object

type String

type String string

func (String) Intern

func (s String) Intern() String

Intern s possibly returning a reference to an already interned string

func (String) LStrip added in v0.2.0

func (s String) LStrip(args Tuple) (Object, error)

func (String) M__add__

func (a String) M__add__(other Object) (Object, error)

func (String) M__bool__

func (s String) M__bool__() (Object, error)

func (String) M__contains__

func (s String) M__contains__(item Object) (Object, error)

func (String) M__eq__

func (a String) M__eq__(other Object) (Object, error)

func (String) M__ge__

func (a String) M__ge__(other Object) (Object, error)

func (String) M__getitem__

func (s String) M__getitem__(key Object) (Object, error)

func (String) M__gt__

func (a String) M__gt__(other Object) (Object, error)

func (String) M__iadd__

func (a String) M__iadd__(other Object) (Object, error)

func (String) M__imod__

func (a String) M__imod__(other Object) (Object, error)

func (String) M__imul__

func (a String) M__imul__(other Object) (Object, error)

func (String) M__le__

func (a String) M__le__(other Object) (Object, error)

func (String) M__len__

func (s String) M__len__() (Object, error)

func (String) M__lt__

func (a String) M__lt__(other Object) (Object, error)

func (String) M__mod__

func (a String) M__mod__(other Object) (Object, error)

4.7.2. printf-style String Formatting

Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.

String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language.

If format requires a single argument, values may be a single non-tuple object. [5] Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

The '%' character, which marks the start of the specifier.

Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).

Conversion flags (optional), which affect the result of some conversion types.

Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.

Length modifier (optional).

Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping. For example:

>>> >>> print('%(language)s has %(number)03d quote types.' % ... {'language': "Python", "number": 2}) Python has 002 quote types.

In this case no * specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

Flag Meaning '#' The value conversion will use the “alternate form” (where defined below). '0' The conversion will be zero padded for numeric values. '-' The converted value is left adjusted (overrides the '0' conversion if both are given). ' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. '+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag).

A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d.

The conversion types are:

Conversion Meaning Notes 'd' Signed integer decimal. 'i' Signed integer decimal. 'o' Signed octal value. (1) 'u' Obsolete type – it is identical to 'd'. (7) 'x' Signed hexadecimal (lowercase). (2) 'X' Signed hexadecimal (uppercase). (2) 'e' Floating point exponential format (lowercase). (3) 'E' Floating point exponential format (uppercase). (3) 'f' Floating point decimal format. (3) 'F' Floating point decimal format. (3) 'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4) 'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4) 'c' Single character (accepts integer or single character string). 'r' String (converts any Python object using repr()). (5) 's' String (converts any Python object using str()). (5) 'a' String (converts any Python object using ascii()). (5) '%' No argument is converted, results in a '%' character in the result. Notes:

The alternate form causes a leading zero ('0') to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.

The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.

The alternate form causes the result to always contain a decimal point, even if no digits follow it.

The precision determines the number of digits after the decimal point and defaults to 6.

The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

The precision determines the number of significant digits before and after the decimal point and defaults to 6.

If precision is N, the output is truncated to N characters.

See PEP 237. Since Python strings have an explicit length, %s conversions do not assume that '\0' is the end of the string.

Changed in version 3.1: %f conversions for numbers whose absolute value is over 1e50 are no longer replaced by %g conversions.

func (String) M__mul__

func (a String) M__mul__(other Object) (Object, error)

func (String) M__ne__

func (a String) M__ne__(other Object) (Object, error)

func (String) M__radd__

func (a String) M__radd__(other Object) (Object, error)

func (String) M__repr__

func (a String) M__repr__() (Object, error)

func (String) M__rmod__

func (a String) M__rmod__(other Object) (Object, error)

func (String) M__rmul__

func (a String) M__rmul__(other Object) (Object, error)

func (String) M__str__

func (a String) M__str__() (Object, error)

func (String) RStrip added in v0.2.0

func (s String) RStrip(args Tuple) (Object, error)

func (String) Replace added in v0.2.0

func (s String) Replace(args Tuple) (Object, error)

func (String) Split added in v0.2.0

func (s String) Split(args Tuple, kwargs StringDict) (Object, error)

func (String) Strip added in v0.2.0

func (s String) Strip(args Tuple) (Object, error)

func (String) Type

func (s String) Type() *Type

Type of this object

type StringDict

type StringDict map[string]Object

String to object dictionary

Used for variables etc where the keys can only be strings

func DictCheck

func DictCheck(obj Object) (StringDict, error)

Checks that obj is exactly a dictionary and returns an error if not

func DictCheckExact

func DictCheckExact(obj Object) (StringDict, error)

Checks that obj is exactly a dictionary and returns an error if not

func NewStringDict

func NewStringDict() StringDict

Make a new dictionary

func NewStringDictSized

func NewStringDictSized(n int) StringDict

Make a new dictionary with reservation for n entries

func (StringDict) Copy

func (d StringDict) Copy() StringDict

Copy a dictionary

func (StringDict) GetDict added in v0.1.0

func (d StringDict) GetDict() StringDict

func (StringDict) M__contains__ added in v0.1.0

func (a StringDict) M__contains__(other Object) (Object, error)

func (StringDict) M__delitem__ added in v0.2.0

func (d StringDict) M__delitem__(key Object) (Object, error)

func (StringDict) M__eq__

func (a StringDict) M__eq__(other Object) (Object, error)

func (StringDict) M__getitem__

func (d StringDict) M__getitem__(key Object) (Object, error)

func (StringDict) M__iter__ added in v0.1.0

func (d StringDict) M__iter__() (Object, error)

Returns a list of keys from the dict

func (StringDict) M__len__ added in v0.2.0

func (a StringDict) M__len__() (Object, error)

func (StringDict) M__ne__

func (a StringDict) M__ne__(other Object) (Object, error)

func (StringDict) M__repr__

func (a StringDict) M__repr__() (Object, error)

func (StringDict) M__setitem__

func (d StringDict) M__setitem__(key, value Object) (Object, error)

func (StringDict) M__str__

func (a StringDict) M__str__() (Object, error)

func (StringDict) Type

func (o StringDict) Type() *Type

Type of this StringDict object

type Traceback

type Traceback struct {
	Next   *Traceback
	Frame  *Frame
	Lasti  int32
	Lineno int32
}

A python Traceback object

func NewTraceback

func NewTraceback(next *Traceback, frame *Frame, lasti, lineno int32) *Traceback

Make a new traceback

func (*Traceback) TracebackDump

func (tb *Traceback) TracebackDump(w io.Writer)

Dump a traceback for tb to w

func (*Traceback) Type

func (o *Traceback) Type() *Type

Type of this object

type TryBlock

type TryBlock struct {
	Type    TryBlockType // what kind of block this is
	Handler int32        // where to jump to find handler
	Level   int          // value stack level to pop to
}

Store information about try blocks

type TryBlockType

type TryBlockType byte

What kind of block this is

const (
	TryBlockSetupLoop TryBlockType = iota
	TryBlockSetupExcept
	TryBlockSetupFinally
	TryBlockExceptHandler
)

type Tuple

type Tuple []Object

func SequenceTuple

func SequenceTuple(v Object) (Tuple, error)

Converts a sequence object v into a Tuple

func (Tuple) Copy

func (t Tuple) Copy() Tuple

Copy a tuple object

func (Tuple) M__add__

func (a Tuple) M__add__(other Object) (Object, error)

func (Tuple) M__bool__

func (t Tuple) M__bool__() (Object, error)

func (Tuple) M__eq__

func (a Tuple) M__eq__(other Object) (Object, error)

func (Tuple) M__getitem__

func (t Tuple) M__getitem__(key Object) (Object, error)

func (Tuple) M__iadd__

func (a Tuple) M__iadd__(other Object) (Object, error)

func (Tuple) M__imul__

func (a Tuple) M__imul__(other Object) (Object, error)

func (Tuple) M__iter__

func (t Tuple) M__iter__() (Object, error)

func (Tuple) M__len__

func (t Tuple) M__len__() (Object, error)

func (Tuple) M__mul__

func (l Tuple) M__mul__(other Object) (Object, error)

func (Tuple) M__ne__

func (a Tuple) M__ne__(other Object) (Object, error)

func (Tuple) M__radd__

func (a Tuple) M__radd__(other Object) (Object, error)

func (Tuple) M__repr__

func (t Tuple) M__repr__() (Object, error)

func (Tuple) M__rmul__

func (a Tuple) M__rmul__(other Object) (Object, error)

func (Tuple) M__str__

func (t Tuple) M__str__() (Object, error)

func (Tuple) Reverse

func (t Tuple) Reverse()

Reverses a tuple (in-place)

func (Tuple) Type

func (o Tuple) Type() *Type

Type of this Tuple object

type Type

type Type struct {
	ObjectType *Type  // Type of this object -- FIXME this is redundant in Base?
	Name       string // For printing, in format "<module>.<name>"
	Doc        string // Documentation string
	//	Methods    StringDict // *PyMethodDef
	//	Members    StringDict // *PyMemberDef
	//	Getset     *PyGetSetDef
	Base *Type
	Dict StringDict
	//	Dictoffset int
	Bases Tuple
	Mro   Tuple // method resolution order
	//	Cache      Object
	//	Subclasses Tuple
	//	Weaklist   Tuple
	New      NewFunc
	Init     InitFunc
	Flags    uint // Flags to define presence of optional/expanded features
	Qualname string
}
var TypeType *Type = &Type{
	Name: "type",
	Doc:  "type(object) -> the object's type\ntype(name, bases, dict) -> a new type",
	Dict: StringDict{},
}

func NewType

func NewType(Name string, Doc string) *Type

Make a new type from a name

For making Go types

func NewTypeX

func NewTypeX(Name string, Doc string, New NewFunc, Init InitFunc) *Type

Make a new type with constructors

For making Go types

func (*Type) Alloc

func (t *Type) Alloc() *Type

Generic object allocator

func (*Type) CalculateMetaclass

func (metatype *Type) CalculateMetaclass(bases Tuple) (*Type, error)

Determine the most derived metatype.

func (*Type) CallMethod

func (t *Type) CallMethod(name string, args Tuple, kwargs StringDict) (Object, bool, error)

Calls method on name

If method not found returns (nil, false, nil)

If method found returns (object, true, err)

May raise exceptions if calling the method failed

func (*Type) Error

func (t *Type) Error() string

Satistfy error interface

func (*Type) GetAttrOrNil

func (t *Type) GetAttrOrNil(name string) Object

Get an attribute from the type

Doesn't call __getattr__ etc

Returns nil if not found

FIXME this isn't totally correct! as we are ignoring getattribute etc See _PyObject_GenericGetAttrWithDict in object.c

func (*Type) GetDict

func (t *Type) GetDict() StringDict

Get the Dict

func (*Type) IsSubtype

func (a *Type) IsSubtype(b *Type) bool

type test with subclassing support reads a IsSubtype of b

func (*Type) Lookup

func (t *Type) Lookup(name string) Object

Internal API to look for a name through the MRO. This returns a borrowed reference, and doesn't set an exception, returning nil instead

func (*Type) M__call__

func (t *Type) M__call__(args Tuple, kwargs StringDict) (Object, error)

Call type()

func (*Type) M__eq__

func (ty *Type) M__eq__(other Object) (Object, error)

FIXME this should be the default?

func (*Type) M__ne__

func (ty *Type) M__ne__(other Object) (Object, error)

FIXME this should be the default?

func (*Type) M__repr__

func (ty *Type) M__repr__() (Object, error)

func (*Type) M__str__

func (ty *Type) M__str__() (Object, error)

func (*Type) NativeGetAttrOrNil

func (t *Type) NativeGetAttrOrNil(name string) Object

Get an attribute from the type of a go type

Doesn't call __getattr__ etc

Returns nil if not found

Doesn't look in the instance dictionary

FIXME this isn't totally correct! as we are ignoring getattribute etc See _PyObject_GenericGetAttrWithDict in object.c

func (*Type) NewType

func (t *Type) NewType(Name string, Doc string, New NewFunc, Init InitFunc) *Type

Make a subclass of a type

For making Go types

func (*Type) NewTypeFlags

func (t *Type) NewTypeFlags(Name string, Doc string, New NewFunc, Init InitFunc, Flags uint) *Type

Make a subclass of a type

For making Go types

func (*Type) Ready

func (t *Type) Ready() error

Ready the type for use

Returns an error on problems

func (*Type) Type

func (t *Type) Type() *Type

Type of this object

type Zip added in v0.1.0

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

A python Zip object

func (*Zip) M__iter__ added in v0.1.0

func (z *Zip) M__iter__() (Object, error)

Zip iterator

func (*Zip) M__next__ added in v0.1.0

func (z *Zip) M__next__() (Object, error)

func (*Zip) Type added in v0.1.0

func (z *Zip) Type() *Type

Type of this object

Jump to

Keyboard shortcuts

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