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
- Variables
- func AttributeName(keyObj Object) (string, error)
- func DebugRepr(self Object) string
- func DeleteAttr(self Object, keyObj Object) error
- func DeleteAttrString(self Object, key string) error
- func DivMod(a, b Object) (Object, Object, error)
- func ExceptionClassCheck(err Object) bool
- func ExceptionGivenMatches(err, exc Object) bool
- func FloatAsFloat64(obj Object) (float64, error)
- func IndexInt(a Object) (int, error)
- func IndexIntCheck(a Object, max int) (int, error)
- func IsException(exception *Type, r interface{}) bool
- func Iterate(obj Object, fn func(Object) bool) error
- func MakeGoInt(a Object) (int, error)
- func MakeGoInt64(a Object) (int64, error)
- func ObjectInit(self Object, args Tuple, kwargs StringDict) error
- func ObjectIsTrue(o Object) bool
- func ParseTuple(args Tuple, format string, results ...*Object) error
- func ParseTupleAndKeywords(args Tuple, kwargs StringDict, format string, kwlist []string, ...) error
- func ReprAsString(self Object) (string, error)
- func SequenceContains(seq, obj Object) (found bool, err error)
- func StrAsString(self Object) (string, error)
- func TracebackDump(err interface{})
- func TypeDelayReady(t *Type)
- func TypeInit(cls Object, args Tuple, kwargs StringDict) error
- func TypeMakeReady() (err error)
- func UnpackTuple(args Tuple, kwargs StringDict, name string, min int, max int, ...) error
- type BigInt
- func (a *BigInt) Float() (Float, error)
- func (a *BigInt) Frexp() (frac float64, exp int)
- func (x *BigInt) GoInt() (int, error)
- func (x *BigInt) GoInt64() (int64, error)
- func (x *BigInt) Int() (Int, error)
- func (a *BigInt) M__abs__() (Object, error)
- func (a *BigInt) M__add__(other Object) (Object, error)
- func (a *BigInt) M__and__(other Object) (Object, error)
- func (a *BigInt) M__bool__() (Object, error)
- func (a *BigInt) M__ceil__() (Object, error)
- func (a *BigInt) M__complex__() (Object, error)
- func (a *BigInt) M__divmod__(other Object) (Object, Object, error)
- func (a *BigInt) M__eq__(other Object) (Object, error)
- func (a *BigInt) M__float__() (Object, error)
- func (a *BigInt) M__floor__() (Object, error)
- func (a *BigInt) M__floordiv__(other Object) (Object, error)
- func (a *BigInt) M__ge__(other Object) (Object, error)
- func (a *BigInt) M__gt__(other Object) (Object, error)
- func (a *BigInt) M__iadd__(other Object) (Object, error)
- func (a *BigInt) M__iand__(other Object) (Object, error)
- func (a *BigInt) M__ifloordiv__(other Object) (Object, error)
- func (a *BigInt) M__ilshift__(other Object) (Object, error)
- func (a *BigInt) M__imod__(other Object) (Object, error)
- func (a *BigInt) M__imul__(other Object) (Object, error)
- func (a *BigInt) M__index__() (Int, error)
- func (a *BigInt) M__int__() (Object, error)
- func (a *BigInt) M__invert__() (Object, error)
- func (a *BigInt) M__ior__(other Object) (Object, error)
- func (a *BigInt) M__ipow__(other, modulus Object) (Object, error)
- func (a *BigInt) M__irshift__(other Object) (Object, error)
- func (a *BigInt) M__isub__(other Object) (Object, error)
- func (a *BigInt) M__itruediv__(other Object) (Object, error)
- func (a *BigInt) M__ixor__(other Object) (Object, error)
- func (a *BigInt) M__le__(other Object) (Object, error)
- func (a *BigInt) M__lshift__(other Object) (Object, error)
- func (a *BigInt) M__lt__(other Object) (Object, error)
- func (a *BigInt) M__mod__(other Object) (Object, error)
- func (a *BigInt) M__mul__(other Object) (Object, error)
- func (a *BigInt) M__ne__(other Object) (Object, error)
- func (a *BigInt) M__neg__() (Object, error)
- func (a *BigInt) M__or__(other Object) (Object, error)
- func (a *BigInt) M__pos__() (Object, error)
- func (a *BigInt) M__pow__(other, modulus Object) (Object, error)
- func (a *BigInt) M__radd__(other Object) (Object, error)
- func (a *BigInt) M__rand__(other Object) (Object, error)
- func (a *BigInt) M__rdivmod__(other Object) (Object, Object, error)
- func (a *BigInt) M__repr__() (Object, error)
- func (a *BigInt) M__rfloordiv__(other Object) (Object, error)
- func (a *BigInt) M__rlshift__(other Object) (Object, error)
- func (a *BigInt) M__rmod__(other Object) (Object, error)
- func (a *BigInt) M__rmul__(other Object) (Object, error)
- func (a *BigInt) M__ror__(other Object) (Object, error)
- func (a *BigInt) M__round__(digits Object) (Object, error)
- func (a *BigInt) M__rpow__(other Object) (Object, error)
- func (a *BigInt) M__rrshift__(other Object) (Object, error)
- func (a *BigInt) M__rshift__(other Object) (Object, error)
- func (a *BigInt) M__rsub__(other Object) (Object, error)
- func (a *BigInt) M__rtruediv__(other Object) (Object, error)
- func (a *BigInt) M__rxor__(other Object) (Object, error)
- func (a *BigInt) M__str__() (Object, error)
- func (a *BigInt) M__sub__(other Object) (Object, error)
- func (a *BigInt) M__truediv__(other Object) (Object, error)
- func (a *BigInt) M__trunc__() (Object, error)
- func (a *BigInt) M__xor__(other Object) (Object, error)
- func (x *BigInt) MaybeInt() Object
- func (o *BigInt) Type() *Type
- type Bool
- type BoundMethod
- type Bytes
- func (a Bytes) M__eq__(other Object) (Object, error)
- func (a Bytes) M__ge__(other Object) (Object, error)
- func (a Bytes) M__gt__(other Object) (Object, error)
- func (a Bytes) M__le__(other Object) (Object, error)
- func (a Bytes) M__lt__(other Object) (Object, error)
- func (a Bytes) M__ne__(other Object) (Object, error)
- func (a Bytes) M__repr__() (Object, error)
- func (a Bytes) M__str__() (Object, error)
- func (o Bytes) Type() *Type
- type Cell
- type ClassMethod
- type Code
- type Complex
- func (a Complex) M__abs__() (Object, error)
- func (a Complex) M__add__(other Object) (Object, error)
- func (a Complex) M__complex__() (Object, error)
- func (a Complex) M__divmod__(other Object) (Object, Object, error)
- func (a Complex) M__eq__(other Object) (Object, error)
- func (a Complex) M__float__() (Object, error)
- func (a Complex) M__floordiv__(other Object) (Object, error)
- func (a Complex) M__ge__(other Object) (Object, error)
- func (a Complex) M__gt__(other Object) (Object, error)
- func (a Complex) M__iadd__(other Object) (Object, error)
- func (a Complex) M__ifloordiv__(other Object) (Object, error)
- func (a Complex) M__imod__(other Object) (Object, error)
- func (a Complex) M__imul__(other Object) (Object, error)
- func (a Complex) M__int__() (Object, error)
- func (a Complex) M__ipow__(other, modulus Object) (Object, error)
- func (a Complex) M__isub__(other Object) (Object, error)
- func (a Complex) M__itruediv__(other Object) (Object, error)
- func (a Complex) M__le__(other Object) (Object, error)
- func (a Complex) M__lt__(other Object) (Object, error)
- func (a Complex) M__mod__(other Object) (Object, error)
- func (a Complex) M__mul__(other Object) (Object, error)
- func (a Complex) M__ne__(other Object) (Object, error)
- func (a Complex) M__neg__() (Object, error)
- func (a Complex) M__pos__() (Object, error)
- func (a Complex) M__pow__(other, modulus Object) (Object, error)
- func (a Complex) M__radd__(other Object) (Object, error)
- func (a Complex) M__rdivmod__(other Object) (Object, Object, error)
- func (a Complex) M__rfloordiv__(other Object) (Object, error)
- func (a Complex) M__rmod__(other Object) (Object, error)
- func (a Complex) M__rmul__(other Object) (Object, error)
- func (a Complex) M__rpow__(other Object) (Object, error)
- func (a Complex) M__rsub__(other Object) (Object, error)
- func (a Complex) M__rtruediv__(other Object) (Object, error)
- func (a Complex) M__sub__(other Object) (Object, error)
- func (a Complex) M__truediv__(other Object) (Object, error)
- func (o Complex) Type() *Type
- type EllipsisType
- type Exception
- type ExceptionInfo
- type File
- type Float
- func (a Float) M__abs__() (Object, error)
- func (a Float) M__add__(other Object) (Object, error)
- func (a Float) M__bool__() (Object, error)
- func (a Float) M__complex__() (Object, error)
- func (a Float) M__divmod__(other Object) (Object, Object, error)
- func (a Float) M__eq__(other Object) (Object, error)
- func (a Float) M__float__() (Object, error)
- func (a Float) M__floordiv__(other Object) (Object, error)
- func (a Float) M__ge__(other Object) (Object, error)
- func (a Float) M__gt__(other Object) (Object, error)
- func (a Float) M__iadd__(other Object) (Object, error)
- func (a Float) M__ifloordiv__(other Object) (Object, error)
- func (a Float) M__imod__(other Object) (Object, error)
- func (a Float) M__imul__(other Object) (Object, error)
- func (a Float) M__int__() (Object, error)
- func (a Float) M__ipow__(other, modulus Object) (Object, error)
- func (a Float) M__isub__(other Object) (Object, error)
- func (a Float) M__itruediv__(other Object) (Object, error)
- func (a Float) M__le__(other Object) (Object, error)
- func (a Float) M__lt__(other Object) (Object, error)
- func (a Float) M__mod__(other Object) (Object, error)
- func (a Float) M__mul__(other Object) (Object, error)
- func (a Float) M__ne__(other Object) (Object, error)
- func (a Float) M__neg__() (Object, error)
- func (a Float) M__pos__() (Object, error)
- func (a Float) M__pow__(other, modulus Object) (Object, error)
- func (a Float) M__radd__(other Object) (Object, error)
- func (a Float) M__rdivmod__(other Object) (Object, Object, error)
- func (a Float) M__repr__() (Object, error)
- func (a Float) M__rfloordiv__(other Object) (Object, error)
- func (a Float) M__rmod__(other Object) (Object, error)
- func (a Float) M__rmul__(other Object) (Object, error)
- func (a Float) M__round__(digitsObj Object) (Object, error)
- func (a Float) M__rpow__(other Object) (Object, error)
- func (a Float) M__rsub__(other Object) (Object, error)
- func (a Float) M__rtruediv__(other Object) (Object, error)
- func (a Float) M__str__() (Object, error)
- func (a Float) M__sub__(other Object) (Object, error)
- func (a Float) M__truediv__(other Object) (Object, error)
- func (o Float) Type() *Type
- type Frame
- func (f *Frame) FastToLocals()
- func (f *Frame) LocalsToFast(clear bool)
- func (f *Frame) Lookup(name string) (obj Object, ok bool)
- func (f *Frame) LookupGlobal(name string) (obj Object, ok bool)
- func (f *Frame) PopBlock()
- func (f *Frame) PushBlock(Type TryBlockType, Handler int32, Level int)
- func (o *Frame) Type() *Type
- type FrozenSet
- type Function
- type Generator
- func (it *Generator) Close() (Object, error)
- func (it *Generator) M__iter__() (Object, error)
- func (it *Generator) M__next__() (Object, error)
- func (it *Generator) Send(arg Object) (Object, error)
- func (it *Generator) Throw(args Tuple, kwargs StringDict) (Object, error)
- func (o *Generator) Type() *Type
- type IGetDict
- type IGoInt
- type IGoInt64
- type I__abs__
- type I__add__
- type I__and__
- type I__bool__
- type I__bytes__
- type I__call__
- type I__ceil__
- type I__complex__
- type I__contains__
- type I__del__
- type I__delattr__
- type I__delete__
- type I__delitem__
- type I__dir__
- type I__divmod__
- type I__enter__
- type I__eq__
- type I__exit__
- type I__float__
- type I__floor__
- type I__floordiv__
- type I__format__
- type I__ge__
- type I__get__
- type I__getattr__
- type I__getattribute__
- type I__getitem__
- type I__gt__
- type I__hash__
- type I__iadd__
- type I__iand__
- type I__ifloordiv__
- type I__ilshift__
- type I__imod__
- type I__imul__
- type I__index__
- type I__init__
- type I__instancecheck__
- type I__int__
- type I__invert__
- type I__ior__
- type I__ipow__
- type I__irshift__
- type I__isub__
- type I__iter__
- type I__itruediv__
- type I__ixor__
- type I__le__
- type I__len__
- type I__length_hint__
- type I__lshift__
- type I__lt__
- type I__mod__
- type I__mul__
- type I__ne__
- type I__neg__
- type I__new__
- type I__next__
- type I__or__
- type I__pos__
- type I__pow__
- type I__radd__
- type I__rand__
- type I__rdivmod__
- type I__repr__
- type I__reversed__
- type I__rfloordiv__
- type I__rlshift__
- type I__rmod__
- type I__rmul__
- type I__ror__
- type I__round__
- type I__rpow__
- type I__rrshift__
- type I__rshift__
- type I__rsub__
- type I__rtruediv__
- type I__rxor__
- type I__set__
- type I__setattr__
- type I__setitem__
- type I__str__
- type I__sub__
- type I__subclasscheck__
- type I__truediv__
- type I__trunc__
- type I__xor__
- type I_close
- type I_generator
- type I_iterator
- type I_send
- type I_throw
- type InitFunc
- type Int
- func (x Int) GoInt() (int, error)
- func (x Int) GoInt64() (int64, error)
- func (a Int) M__abs__() (Object, error)
- func (a Int) M__add__(other Object) (Object, error)
- func (a Int) M__and__(other Object) (Object, error)
- func (a Int) M__bool__() (Object, error)
- func (a Int) M__ceil__() (Object, error)
- func (a Int) M__complex__() (Object, error)
- func (a Int) M__divmod__(other Object) (Object, Object, error)
- func (a Int) M__eq__(other Object) (Object, error)
- func (a Int) M__float__() (Object, error)
- func (a Int) M__floor__() (Object, error)
- func (a Int) M__floordiv__(other Object) (Object, error)
- func (a Int) M__ge__(other Object) (Object, error)
- func (a Int) M__gt__(other Object) (Object, error)
- func (a Int) M__iadd__(other Object) (Object, error)
- func (a Int) M__iand__(other Object) (Object, error)
- func (a Int) M__ifloordiv__(other Object) (Object, error)
- func (a Int) M__ilshift__(other Object) (Object, error)
- func (a Int) M__imod__(other Object) (Object, error)
- func (a Int) M__imul__(other Object) (Object, error)
- func (a Int) M__index__() (Int, error)
- func (a Int) M__int__() (Object, error)
- func (a Int) M__invert__() (Object, error)
- func (a Int) M__ior__(other Object) (Object, error)
- func (a Int) M__ipow__(other, modulus Object) (Object, error)
- func (a Int) M__irshift__(other Object) (Object, error)
- func (a Int) M__isub__(other Object) (Object, error)
- func (a Int) M__itruediv__(other Object) (Object, error)
- func (a Int) M__ixor__(other Object) (Object, error)
- func (a Int) M__le__(other Object) (Object, error)
- func (a Int) M__lshift__(other Object) (Object, error)
- func (a Int) M__lt__(other Object) (Object, error)
- func (a Int) M__mod__(other Object) (Object, error)
- func (a Int) M__mul__(other Object) (Object, error)
- func (a Int) M__ne__(other Object) (Object, error)
- func (a Int) M__neg__() (Object, error)
- func (a Int) M__or__(other Object) (Object, error)
- func (a Int) M__pos__() (Object, error)
- func (a Int) M__pow__(other, modulus Object) (Object, error)
- func (a Int) M__radd__(other Object) (Object, error)
- func (a Int) M__rand__(other Object) (Object, error)
- func (a Int) M__rdivmod__(other Object) (Object, Object, error)
- func (a Int) M__repr__() (Object, error)
- func (a Int) M__rfloordiv__(other Object) (Object, error)
- func (a Int) M__rlshift__(other Object) (Object, error)
- func (a Int) M__rmod__(other Object) (Object, error)
- func (a Int) M__rmul__(other Object) (Object, error)
- func (a Int) M__ror__(other Object) (Object, error)
- func (a Int) M__round__(digits Object) (Object, error)
- func (a Int) M__rpow__(other Object) (Object, error)
- func (a Int) M__rrshift__(other Object) (Object, error)
- func (a Int) M__rshift__(other Object) (Object, error)
- func (a Int) M__rsub__(other Object) (Object, error)
- func (a Int) M__rtruediv__(other Object) (Object, error)
- func (a Int) M__rxor__(other Object) (Object, error)
- func (a Int) M__str__() (Object, error)
- func (a Int) M__sub__(other Object) (Object, error)
- func (a Int) M__truediv__(other Object) (Object, error)
- func (a Int) M__trunc__() (Object, error)
- func (a Int) M__xor__(other Object) (Object, error)
- func (o Int) Type() *Type
- type InternalMethod
- type Iterator
- type List
- func (l *List) Append(item Object)
- func (l *List) Copy() *List
- func (a *List) DelItem(i int)
- func (l *List) Extend(items []Object)
- func (l *List) ExtendSequence(seq Object) error
- func (l *List) Len() int
- func (a *List) M__add__(other Object) (Object, error)
- func (l *List) M__bool__() (Object, error)
- func (a *List) M__delitem__(key Object) (Object, error)
- func (a *List) M__eq__(other Object) (Object, error)
- func (l *List) M__getitem__(key Object) (Object, error)
- func (a *List) M__iadd__(other Object) (Object, error)
- func (a *List) M__imul__(other Object) (Object, error)
- func (l *List) M__iter__() (Object, error)
- func (l *List) M__len__() (Object, error)
- func (l *List) M__mul__(other Object) (Object, error)
- func (a *List) M__ne__(other Object) (Object, error)
- func (a *List) M__radd__(other Object) (Object, error)
- func (l *List) M__repr__() (Object, error)
- func (a *List) M__rmul__(other Object) (Object, error)
- func (l *List) M__setitem__(key, value Object) (Object, error)
- func (l *List) M__str__() (Object, error)
- func (l *List) Resize(newSize int)
- func (o *List) Type() *Type
- type Method
- func (m *Method) Call(self Object, args Tuple) (Object, error)
- func (m *Method) CallWithKeywords(self Object, args Tuple, kwargs StringDict) (Object, error)
- func (m *Method) Internal() InternalMethod
- func (m *Method) M__call__(args Tuple, kwargs StringDict) (Object, error)
- func (m *Method) M__eq__(other Object) (Object, error)
- func (m *Method) M__get__(instance, owner Object) (Object, error)
- func (m *Method) M__ne__(other Object) (Object, error)
- func (o *Method) Type() *Type
- type Module
- type NewFunc
- type NoneType
- type Object
- func Abs(a Object) (Object, error)
- func Add(a, b Object) (Object, error)
- func And(a, b Object) (Object, error)
- func BuiltinImport(self Object, args Tuple, kwargs StringDict, currentGlobal StringDict) (Object, error)
- func BytesNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)
- func Call(fn Object, args Tuple, kwargs StringDict) (Object, error)
- func ClassMethodNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)
- func ComplexNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func DelItem(self Object, key Object) (Object, error)
- func Eq(a Object, b Object) (Object, error)
- func ExceptionNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func FloatFromString(str string) (Object, error)
- func FloatNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func FloorDiv(a, b Object) (Object, error)
- func Ge(a Object, b Object) (Object, error)
- func GetAttr(self Object, keyObj Object) (res Object, err error)
- func GetAttrString(self Object, key string) (res Object, err error)
- func GetItem(self Object, key Object) (Object, error)
- func Gt(a Object, b Object) (Object, error)
- func IAdd(a, b Object) (Object, error)
- func IAnd(a, b Object) (Object, error)
- func IFloorDiv(a, b Object) (Object, error)
- func ILshift(a, b Object) (Object, error)
- func IMod(a, b Object) (Object, error)
- func IMul(a, b Object) (Object, error)
- func IOr(a, b Object) (Object, error)
- func IPow(a, b, c Object) (Object, error)
- func IRshift(a, b Object) (Object, error)
- func ISub(a, b Object) (Object, error)
- func ITrueDiv(a, b Object) (Object, error)
- func IXor(a, b Object) (Object, error)
- func ImportModuleLevelObject(name string, globals, locals StringDict, fromlist Tuple, level int) (Object, error)
- func IntFromString(str string, base int) (Object, error)
- func IntNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func Invert(a Object) (Object, error)
- func Iter(a Object) (Object, error)
- func Le(a Object, b Object) (Object, error)
- func Len(self Object) (Object, error)
- func ListNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)
- func Lshift(a, b Object) (Object, error)
- func Lt(a Object, b Object) (Object, error)
- func MakeBool(a Object) (Object, error)
- func MakeComplex(a Object) (Object, error)
- func MakeFloat(a Object) (Object, error)
- func MakeInt(a Object) (Object, error)
- func Mod(a, b Object) (Object, error)
- func Mul(a, b Object) (Object, error)
- func Ne(a Object, b Object) (Object, error)
- func Neg(a Object) (Object, error)
- func Next(self Object) (obj Object, err error)
- func Not(a Object) (Object, error)
- func ObjectGetAttr(o Object, attr string) Object
- func ObjectNew(t *Type, args Tuple, kwargs StringDict) (Object, error)
- func ObjectRepr(o Object) Object
- func Or(a, b Object) (Object, error)
- func Pos(a Object) (Object, error)
- func Pow(a, b, c Object) (Object, error)
- func RangeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func Repr(self Object) (Object, error)
- func Rshift(a, b Object) (Object, error)
- func Send(self, value Object) (Object, error)
- func SetAttr(self Object, keyObj Object, value Object) (Object, error)
- func SetAttrString(self Object, key string, value Object) (Object, error)
- func SetItem(self Object, key Object, value Object) (Object, error)
- func SetNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func SliceNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func StaticMethodNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)
- func Str(self Object) (Object, error)
- func StrNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func Sub(a, b Object) (Object, error)
- func TrueDiv(a, b Object) (Object, error)
- func TupleNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)
- func TypeCall(self Object, name string, args Tuple, kwargs StringDict) (Object, bool, error)
- func TypeCall0(self Object, name string) (Object, bool, error)
- func TypeCall1(self Object, name string, arg Object) (Object, bool, error)
- func TypeCall2(self Object, name string, arg1, arg2 Object) (Object, bool, error)
- func TypeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
- func XImportModuleLevelObject(nameObj, given_globals, locals, given_fromlist Object, level int) (Object, error)
- func Xor(a, b Object) (Object, error)
- type Property
- type PyCFunction
- type PyCFunction1Arg
- type PyCFunctionNoArgs
- type PyCFunctionWithKeywords
- type Range
- type RangeIterator
- type Set
- func (s *Set) Add(item Object)
- func (s *Set) M__bool__() (Object, error)
- func (a *Set) M__eq__(other Object) (Object, error)
- func (s *Set) M__iter__() (Object, error)
- func (s *Set) M__len__() (Object, error)
- func (a *Set) M__ne__(other Object) (Object, error)
- func (o *Set) Type() *Type
- func (s *Set) Update(items []Object)
- type SetValue
- type Slice
- type StaticMethod
- type String
- func (s String) Intern() String
- func (a String) M__add__(other Object) (Object, error)
- func (s String) M__bool__() (Object, error)
- func (s String) M__contains__(item Object) (Object, error)
- func (a String) M__eq__(other Object) (Object, error)
- func (a String) M__ge__(other Object) (Object, error)
- func (s String) M__getitem__(key Object) (Object, error)
- func (a String) M__gt__(other Object) (Object, error)
- func (a String) M__iadd__(other Object) (Object, error)
- func (a String) M__imod__(other Object) (Object, error)
- func (a String) M__imul__(other Object) (Object, error)
- func (a String) M__le__(other Object) (Object, error)
- func (s String) M__len__() (Object, error)
- func (a String) M__lt__(other Object) (Object, error)
- func (a String) M__mod__(other Object) (Object, error)
- func (a String) M__mul__(other Object) (Object, error)
- func (a String) M__ne__(other Object) (Object, error)
- func (a String) M__radd__(other Object) (Object, error)
- func (a String) M__repr__() (Object, error)
- func (a String) M__rmod__(other Object) (Object, error)
- func (a String) M__rmul__(other Object) (Object, error)
- func (a String) M__str__() (Object, error)
- func (s String) Type() *Type
- type StringDict
- func (d StringDict) Copy() StringDict
- func (a StringDict) M__eq__(other Object) (Object, error)
- func (d StringDict) M__getitem__(key Object) (Object, error)
- func (a StringDict) M__ne__(other Object) (Object, error)
- func (a StringDict) M__repr__() (Object, error)
- func (d StringDict) M__setitem__(key, value Object) (Object, error)
- func (a StringDict) M__str__() (Object, error)
- func (o StringDict) Type() *Type
- type Traceback
- type TryBlock
- type TryBlockType
- type Tuple
- func (t Tuple) Copy() Tuple
- func (a Tuple) M__add__(other Object) (Object, error)
- func (t Tuple) M__bool__() (Object, error)
- func (a Tuple) M__eq__(other Object) (Object, error)
- func (t Tuple) M__getitem__(key Object) (Object, error)
- func (a Tuple) M__iadd__(other Object) (Object, error)
- func (a Tuple) M__imul__(other Object) (Object, error)
- func (t Tuple) M__iter__() (Object, error)
- func (t Tuple) M__len__() (Object, error)
- func (l Tuple) M__mul__(other Object) (Object, error)
- func (a Tuple) M__ne__(other Object) (Object, error)
- func (a Tuple) M__radd__(other Object) (Object, error)
- func (t Tuple) M__repr__() (Object, error)
- func (a Tuple) M__rmul__(other Object) (Object, error)
- func (t Tuple) M__str__() (Object, error)
- func (t Tuple) Reverse()
- func (o Tuple) Type() *Type
- type Type
- func (t *Type) Alloc() *Type
- func (metatype *Type) CalculateMetaclass(bases Tuple) (*Type, error)
- func (t *Type) CallMethod(name string, args Tuple, kwargs StringDict) (Object, bool, error)
- func (t *Type) Error() string
- func (t *Type) GetAttrOrNil(name string) Object
- func (t *Type) GetDict() StringDict
- func (a *Type) IsSubtype(b *Type) bool
- func (t *Type) Lookup(name string) Object
- func (t *Type) M__call__(args Tuple, kwargs StringDict) (Object, error)
- func (ty *Type) M__eq__(other Object) (Object, error)
- func (ty *Type) M__ne__(other Object) (Object, error)
- func (ty *Type) M__repr__() (Object, error)
- func (ty *Type) M__str__() (Object, error)
- func (t *Type) NativeGetAttrOrNil(name string) Object
- func (t *Type) NewType(Name string, Doc string, New NewFunc, Init InitFunc) *Type
- func (t *Type) NewTypeFlags(Name string, Doc string, New NewFunc, Init InitFunc, Flags uint) *Type
- func (t *Type) Ready() error
- func (t *Type) Type() *Type
Constants ¶
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 )
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 )
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 )
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 )
const NAME_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
Variables ¶
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) )
var ( StringDictType = NewType("dict", dictDoc) DictType = NewType("dict", dictDoc) )
var ( EllipsisTypeType = NewType("EllipsisType", "") Ellipsis = EllipsisType(struct{}{}) )
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 )
var ( NoneTypeType = NewType("NoneType", "") // And the ubiquitous None = NoneType(struct{}{}) )
var ( // Set in vm/eval.go - to avoid circular import VmRun func(globals, locals StringDict, code *Code, closure Tuple) (res Object, err error) VmRunFrame func(frame *Frame) (res Object, err error) VmEvalCodeEx func(co *Code, globals, locals StringDict, args []Object, kws StringDict, defs []Object, kwdefs StringDict, closure Tuple) (retval Object, err error) // See compile/compile.go - set to avoid circular import Compile func(str, filename, mode string, flags int, dont_inherit bool) (Object, error) )
Some well known objects
var BigIntType = NewType("bigint", "Holds large integers")
var BoundMethodType = NewType("boundmethod", "boundmethod object")
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)
var CellType = NewType("cell", "cell object")
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)
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.")
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)
var FileType = NewTypeX("file", `represents an open file`, nil, nil)
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)
var FrameType = NewType("frame", "Represents a stack frame")
var FrozenSetType = NewType("frozenset", "frozenset() -> empty frozenset object\nfrozenset(iterable) -> frozenset object\n\nBuild an immutable unordered collection of unique elements.")
var FunctionType = NewType("function", "A python function")
var GeneratorType = NewType("generator", "generator object")
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)
var IteratorType = NewType("iterator", "iterator type")
var ListType = ObjectType.NewType("list", "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items", ListNew, nil)
var MethodType = NewType("method", "method object")
var ModuleType = NewType("module", "module object")
var ObjectType = &Type{ Name: "object", Doc: "The most base type", Flags: TPFLAGS_BASETYPE, Dict: StringDict{}, }
var PropertyType = NewType("property", "property object")
var RangeIteratorType = NewType("range_iterator", `range_iterator object`)
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)
var SetType = NewTypeX("set", "set() -> new empty set object\nset(iterable) -> new set object\n\nBuild an unordered collection of unique elements.", SetNew, nil)
var SliceType = NewType("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]).`)
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)
var StringType = ObjectType.NewType("string", `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)
var TracebackType = NewType("traceback", "A python traceback")
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)
Functions ¶
func AttributeName ¶
AttributeName converts an Object to a string, raising a TypeError if it wasn't a String
func DivMod ¶
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 ¶
Checks that the object passed in is a class and is an exception
func ExceptionGivenMatches ¶
Check to see if err matches exc
exc can be a tuple
Used in except statements
func IndexInt ¶
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 ¶
As IndexInt but if index is -ve addresses it from the end
If index is out of range throws IndexError
func IsException ¶
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 ¶
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 ObjectInit ¶
func ObjectInit(self Object, args Tuple, kwargs StringDict) error
func ObjectIsTrue ¶ added in v0.0.1
Return whether the object is True or not
func ParseTuple ¶
Parse tuple only
func ParseTupleAndKeywords ¶
func ParseTupleAndKeywords(args Tuple, kwargs StringDict, format string, kwlist []string, results ...*Object) error
ParseTupleAndKeywords
func SequenceContains ¶
SequenceContains returns True if obj is in seq
func TypeDelayReady ¶
func TypeDelayReady(t *Type)
TypeDelayReady stores the list of types to initialise
Call MakeReady when all initialised
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 ¶
func BigIntCheck ¶
Checks that obj is exactly a bigInd and returns an error if not
func BigIntCheckExact ¶
Checks that obj is exactly a BigInt and returns an error if not
func (*BigInt) Float ¶
Truncates to Float
If it is outside the range of an Float it will return an error
func (*BigInt) GoInt ¶
Truncates to go int
If it is outside the range of an go int it will return an error
func (*BigInt) GoInt64 ¶
Truncates to go int64
If it is outside the range of an go int64 it will return an error
func (*BigInt) M__complex__ ¶
func (*BigInt) M__float__ ¶
func (*BigInt) M__floor__ ¶
func (*BigInt) M__index__ ¶
func (*BigInt) M__invert__ ¶
func (*BigInt) M__trunc__ ¶
type Bool ¶
type Bool bool
func (Bool) M__index__ ¶
type BoundMethod ¶
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
type ClassMethod ¶
type ClassMethod struct { Callable Object Dict StringDict }
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 ¶
Use co_lnotab to compute the line number from a bytecode index, addrq. See lnotab_notes.txt for the details of the lnotab representation.
type EllipsisType ¶
type EllipsisType struct{}
func (EllipsisType) M__bool__ ¶
func (a EllipsisType) M__bool__() (Object, error)
func (EllipsisType) M__repr__ ¶
func (a EllipsisType) M__repr__() (Object, error)
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 ¶
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) M__getattr__ ¶
FIXME prototype __getattr__ before we do introspection!
type ExceptionInfo ¶
A python exception info block
func (*ExceptionInfo) TracebackDump ¶
func (exc *ExceptionInfo) TracebackDump(w io.Writer)
Dump a traceback for exc to w
type Float ¶
type Float float64
func FloatCheck ¶
Returns the float value of obj if it is a float subclass
func FloatCheckExact ¶
Returns the float value of obj if it is exactly a float
func (Float) M__complex__ ¶
func (Float) M__float__ ¶
type Frame ¶
type Frame struct { // Back *Frame // previous frame, or nil 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(globals, locals StringDict, code *Code, closure Tuple) *Frame
Make a new frame for a code object
func (*Frame) LocalsToFast ¶
Merge frame Locals into fast locals
func (*Frame) Lookup ¶
Python names are looked up in three scopes
First the local scope Next the module global scope And finally the builtins
func (*Frame) LookupGlobal ¶
Python globals are looked up in two scopes
The module global scope And finally the builtins
type FrozenSet ¶
type FrozenSet struct {
Set
}
func NewFrozenSetFromItems ¶
Make a new set with the items passed in
type Function ¶
type Function struct { Code *Code // A code object, the __code__ attribute 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 Module Object // The __module__ attribute, can be anything Annotations StringDict // Annotations, a dict or NULL Qualname string // The qualified name }
A python Function object
func NewFunction ¶
func NewFunction(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) M__call__ ¶
func (f *Function) M__call__(args Tuple, kwargs StringDict) (Object, error)
Call a function
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 (*Generator) Close ¶
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__next__ ¶
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 ¶
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.
type I__bool__ ¶
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__ ¶
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__ ¶
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__ ¶
object.__complex__(self)
type I__contains__ ¶
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__ ¶
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__ ¶
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__ ¶
Called to delete the attribute on an instance instance of the owner class. object.__delete__(self, instance)
type I__delitem__ ¶
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__ ¶
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__ ¶
object.__divmod__(self, other)
type I__enter__ ¶
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__exit__ ¶
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__floor__ ¶
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__ ¶
object.__floordiv__(self, other)
type I__format__ ¶
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__get__ ¶
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__ ¶
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__ ¶
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__ ¶
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__hash__ ¶
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__ifloordiv__ ¶
object.__ifloordiv__(self, other)
type I__ilshift__ ¶
object.__ilshift__(self, other)
type I__init__ ¶
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__ ¶
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__invert__ ¶
object.__invert__(self)
type I__irshift__ ¶
object.__irshift__(self, other)
type I__iter__ ¶
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__ ¶
object.__itruediv__(self, other)
type I__len__ ¶
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__ ¶
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__ ¶
object.__lshift__(self, other)
type I__lt__ ¶
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__new__ ¶
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__rdivmod__ ¶
object.__rdivmod__(self, other)
type I__repr__ ¶
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__ ¶
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__ ¶
object.__rfloordiv__(self, other)
type I__rlshift__ ¶
object.__rlshift__(self, other)
type I__round__ ¶
object.__round__(self, n)
type I__rrshift__ ¶
object.__rrshift__(self, other)
type I__rshift__ ¶
object.__rshift__(self, other)
type I__rtruediv__ ¶
object.__rtruediv__(self, other)
type I__set__ ¶
Called to set the attribute on an instance of the owner class to a new value. object.__set__(self, instance, value)
type I__setattr__ ¶
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__ ¶
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__ ¶
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__subclasscheck__ ¶
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__ ¶
object.__truediv__(self, other)
type I__trunc__ ¶
Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__().
type I_generator ¶
type I_generator interface { I_iterator I_send I_throw I_close }
Interface all generators must satisfy
type I_iterator ¶
Interface all iterators must satisfy
type Int ¶
type Int int64
func Index ¶
Index the python Object returning an Int
Will raise TypeError if Index can't be run on this object
func (Int) GoInt ¶
Truncates to go int
If it is outside the range of an go int it will return an error
func (Int) GoInt64 ¶
Truncates to go int64
If it is outside the range of an go int64 it will return an error
func (Int) M__complex__ ¶
func (Int) M__float__ ¶
func (Int) M__floor__ ¶
func (Int) M__index__ ¶
func (Int) M__invert__ ¶
func (Int) M__trunc__ ¶
type InternalMethod ¶
type InternalMethod int
Internal method types implemented within eval.go
const ( InternalMethodNone InternalMethod = iota InternalMethodGlobals InternalMethodLocals InternalMethodImport InternalMethodEval InternalMethodExec )
type Iterator ¶
A python Iterator 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 NewListWithCapacity ¶
Make a new empty list with given capacity
func SequenceList ¶
Converts a sequence object v into a List
func (*List) ExtendSequence ¶
Extends the list with the sequence passed in
func (*List) M__delitem__ ¶
Removes items from a list
type Method ¶
type Method struct { // Name of this function Name string // Doc string Doc string // Flags - see METH_* flags Flags int // contains filtered or unexported fields }
A python Method object
func MustNewMethod ¶
As NewMethod but panics on error
func (*Method) CallWithKeywords ¶
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
type Module ¶
type Module struct { Name string Doc string Globals StringDict }
A python Module object
func NewModule ¶
func NewModule(name, doc string, methods []*Method, globals StringDict) *Module
Define a new module
type Object ¶
type Object interface {
Type() *Type
}
A python object
func Abs ¶
Abs the python Object returning an Object
Will raise TypeError if Abs can't be run on this object
func Add ¶
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 ¶
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(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 Eq ¶
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 FloatFromString ¶
FloatFromString turns a string into a Float
func FloatNew ¶
func FloatNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
FloatNew
func FloorDiv ¶
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 ¶
Ge two python objects returning a boolean result
Will raise TypeError if Ge can't be run on this object
func GetAttr ¶
GetAttrErr - returns the result or an err to be raised if not found
If not found an AttributeError will be returned
func GetAttrString ¶
GetAttrString - returns the result or an err to be raised if not found
If not found err will be an AttributeError
func Gt ¶
Gt two python objects returning a boolean result
Will raise TypeError if Gt can't be run on this object
func ImportModuleLevelObject ¶
func ImportModuleLevelObject(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 ¶
Create an Int (or BigInt) from the string passed in
FIXME check this is 100% python compatible
func Invert ¶
Invert the python Object returning an Object
Will raise TypeError if Invert can't be run on this object
func Iter ¶
Iter the python Object returning an Object
Will raise TypeError if Iter can't be run on this object
func Le ¶
Le two python objects returning a boolean result
Will raise TypeError if Le can't be run on this object
func ListNew ¶
func ListNew(metatype *Type, args Tuple, kwargs StringDict) (res Object, err error)
ListNew
func Lshift ¶
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 ¶
Lt two python objects returning a boolean result
Will raise TypeError if Lt can't be run on this object
func MakeBool ¶
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 ¶
MakeComplex the python Object returning an Object
Will raise TypeError if MakeComplex can't be run on this object
func MakeFloat ¶
MakeFloat the python Object returning an Object
Will raise TypeError if MakeFloat can't be run on this object
func MakeInt ¶
MakeInt the python Object returning an Object
Will raise TypeError if MakeInt can't be run on this object
func Mod ¶
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 ¶
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 ¶
Ne two python objects returning a boolean result
Will raise TypeError if Ne can't be run on this object
func Neg ¶
Neg the python Object returning an Object
Will raise TypeError if Neg can't be run on this object
func Next ¶
Call __next__ for the python object
Returns the next object ¶
err == StopIteration or subclass when finished
func ObjectGetAttr ¶
Gets the attribute attr from object or returns nil
func Or ¶
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 ¶
Pos the python Object returning an Object
Will raise TypeError if Pos can't be run on this object
func Pow ¶
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 Rshift ¶
Rshift two python objects together returning an Object
Will raise TypeError if can't be rshift can't be run on these objects
func SetAttrString ¶
SetAttrString
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 Sub ¶
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 ¶
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 ¶
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 TypeNew ¶
func TypeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error)
Create a new type
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
type PyCFunction ¶
Called with self and a tuple of args
type PyCFunction1Arg ¶
Called with one (unnamed) parameter 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 ¶
A python Range object FIXME one day support BigInts too!
type RangeIterator ¶
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
type Set ¶
type Set struct {
// contains filtered or unexported fields
}
func NewSetFromItems ¶
Make a new set with the items passed in
func NewSetWithCapacity ¶
Make a new empty set with capacity for n items
type Slice ¶
A python Slice object
func (*Slice) GetIndices ¶
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.
type StaticMethod ¶
type StaticMethod struct { Callable Object Dict StringDict }
type String ¶
type String string
func (String) M__mod__ ¶
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.
type StringDict ¶
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 NewStringDictSized ¶
func NewStringDictSized(n int) StringDict
Make a new dictionary with reservation for n entries
func (StringDict) M__getitem__ ¶
func (d StringDict) M__getitem__(key 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)
type Traceback ¶
A python Traceback object
func NewTraceback ¶
Make a new traceback
func (*Traceback) TracebackDump ¶
Dump a traceback for tb to w
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 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 (*Type) CalculateMetaclass ¶
Determine the most derived metatype.
func (*Type) CallMethod ¶
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) GetAttrOrNil ¶
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) Lookup ¶
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) NativeGetAttrOrNil ¶
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
Source Files ¶
- args.go
- arithmetic.go
- bigint.go
- bool.go
- boundmethod.go
- bytes.go
- cell.go
- classmethod.go
- code.go
- complex.go
- dict.go
- ellipsis.go
- exception.go
- file.go
- float.go
- frame.go
- function.go
- generator.go
- import.go
- int.go
- internal.go
- iterator.go
- list.go
- method.go
- module.go
- none.go
- object.go
- property.go
- py.go
- range.go
- sequence.go
- set.go
- slice.go
- staticmethod.go
- string.go
- traceback.go
- tuple.go
- type.go