Documentation
¶
Overview ¶
Package objects ports the gating subset of cpython/Objects/. v0.2 covers the object protocol, the type slot table, and the concrete builtins needed to construct a dict, hash a tuple, and iterate a list. Strings, bytes, set, exceptions, and the cycle collector arrive in later phases (see notes/Spec/1700/).
Set and frozenset objects. Mirrors CPython's open-addressed hash table layout. frozenset is an immutable set that supports all read operations but disallows mutation; it stores its hash lazily.
CPython: Objects/setobject.c
Index ¶
- Constants
- Variables
- func AdjustIndices(length int, start, stop *int, step int) int
- func ClearInterned()
- func Contains(o, v Object) (bool, error)
- func Decref(o Object)
- func DelAttr(o Object, name Object) error
- func DelItem(o, key Object) error
- func Format(o Object, spec string) (string, error)
- func GenericSetAttr(o Object, name Object, value Object) error
- func Hash(o Object) (int64, error)
- func HashBytes(src []byte) int64
- func HashString(s string) int64
- func Incref(o Object)
- func IndexCheck(o Object) bool
- func InternInPlace(p *Object)
- func InternedCount() int
- func Is(a, b Object) bool
- func IsAlphaRune(r rune) bool
- func IsBool(o Object) bool
- func IsCasedRune(r rune) bool
- func IsDecimalRune(r rune) bool
- func IsDigitRune(r rune) bool
- func IsEllipsis(o Object) bool
- func IsFalse(o Object) bool
- func IsLowerRune(r rune) bool
- func IsNone(o Object) bool
- func IsNotImplemented(o Object) bool
- func IsNumericRune(r rune) bool
- func IsPrintableRune(r rune) bool
- func IsSpaceRune(r rune) bool
- func IsSubtype(sub, super *Type) bool
- func IsTitleRune(r rune) bool
- func IsTrue(o Object) bool
- func IsTruthy(o Object) (bool, error)
- func IsUpperRune(r rune) bool
- func IsXIDContinueRune(r rune) bool
- func IsXIDStartRune(r rune) bool
- func Length(o Object) (int, error)
- func LookupDescriptor(t *Type, name string) (Object, *Type)
- func MakeStrTrans(from, to, drop string) (map[rune]rune, error)
- func MappingCheck(o Object) bool
- func MappingDelItem(o, key Object) error
- func MappingDelItemString(o Object, key string) error
- func MappingHasKey(o, key Object) bool
- func MappingHasKeyString(o Object, key string) bool
- func MappingHasKeyStringWithError(o Object, key string) (bool, error)
- func MappingHasKeyWithError(o, key Object) (bool, error)
- func MappingLength(o Object) (int, error)
- func MappingSetItemString(o Object, key string, value Object) error
- func MappingSize(o Object) (int, error)
- func MissingArgumentsError(qualname, kind string, names []string) error
- func MultipleValuesForArgumentError(qualname, name string) error
- func PositionalOnlyAsKeywordError(qualname string, names []string) error
- func Repr(o Object) (string, error)
- func RichCmpBool(a, b Object, op CompareOp) (bool, error)
- func SequenceCheck(s Object) bool
- func SequenceContains(s, o Object) (bool, error)
- func SequenceCount(s, o Object) (int, error)
- func SequenceDelItem(s Object, i int) error
- func SequenceIndex(s, o Object) (int, error)
- func SequenceSetItem(s Object, i int, v Object) error
- func SequenceSize(s Object) (int, error)
- func SetAttr(o Object, name Object, value Object) error
- func SetItem(o, key, value Object) error
- func SetTypeDescr(t *Type, name string, d Object)
- func Str(o Object) (string, error)
- func StrCapitalize(s string) string
- func StrCaseFold(s string) string
- func StrCenter(s string, width int, fillchar rune) string
- func StrCount(s, needle string, start, end int) int
- func StrEndsWith(s, suffix string, start, end int) bool
- func StrExpandTabs(s string, tabsize int) string
- func StrFind(s, needle string, start, end int) int
- func StrIndex(s, needle string, start, end int) (int, error)
- func StrIsASCII(s string) bool
- func StrIsAlnum(s string) bool
- func StrIsAlpha(s string) bool
- func StrIsDecimal(s string) bool
- func StrIsDigit(s string) bool
- func StrIsIdentifier(s string) bool
- func StrIsLower(s string) bool
- func StrIsNumeric(s string) bool
- func StrIsPrintable(s string) bool
- func StrIsSpace(s string) bool
- func StrIsTitle(s string) bool
- func StrIsUpper(s string) bool
- func StrJoin(sep string, parts []Object) (string, error)
- func StrLJust(s string, width int, fillchar rune) string
- func StrLStrip(s, chars string) string
- func StrLower(s string) string
- func StrPartition(s, sep string) (string, string, string, error)
- func StrRFind(s, needle string, start, end int) int
- func StrRIndex(s, needle string, start, end int) (int, error)
- func StrRJust(s string, width int, fillchar rune) string
- func StrRPartition(s, sep string) (string, string, string, error)
- func StrRSplit(s, sep string, maxsplit int) ([]string, error)
- func StrRStrip(s, chars string) string
- func StrReplace(s, old, newS string, count int) string
- func StrSplit(s, sep string, maxsplit int) ([]string, error)
- func StrSplitLines(s string, keepends bool) []string
- func StrStartsWith(s, prefix string, start, end int) bool
- func StrStrip(s, chars string) string
- func StrSwapCase(s string) string
- func StrTitle(s string) string
- func StrTranslate(s string, table map[rune]rune) string
- func StrUpper(s string) string
- func StrZFill(s string, width int) string
- func ToLowerRune(r rune) rune
- func ToTitleRune(r rune) rune
- func ToUpperRune(r rune) rune
- func TooManyPositionalError(qualname string, given, atLeast, atMost, kwonlyGiven int) error
- func UnexpectedKeywordError(qualname, name string) error
- func UnpackKwargs(kwargs *Dict) (*Tuple, []Object, error)
- func VectorcallNargs(nargsf uint) int
- type AsyncGenerator
- func (g *AsyncGenerator) Aclose() Object
- func (g *AsyncGenerator) Anext() Object
- func (g *AsyncGenerator) Asend(v Object) Object
- func (g *AsyncGenerator) Athrow(err error) Object
- func (g *AsyncGenerator) Close() error
- func (g *AsyncGenerator) Send(v Object) (Object, error)
- func (g *AsyncGenerator) Throw(err error) (Object, error)
- type AsyncMethods
- type Bool
- type BoundMethod
- type BuiltinFunction
- type ByteArray
- type Bytes
- func (b *Bytes) Bytes() []byte
- func (b *Bytes) Center(width int, fill byte) *Bytes
- func (b *Bytes) Count(sub []byte, start, end int) int
- func (b *Bytes) EndsWith(suffix []byte, start, end int) bool
- func (b *Bytes) ExpandTabs(tabsize int) *Bytes
- func (b *Bytes) Find(sub []byte, start, end int) int
- func (b *Bytes) Hex(sep byte, bytesPerSep int) string
- func (b *Bytes) Index(sub []byte, start, end int) (int, error)
- func (b *Bytes) Join(seq []Object) (*Bytes, error)
- func (b *Bytes) LJust(width int, fill byte) *Bytes
- func (b *Bytes) LStrip(chars []byte) *Bytes
- func (b *Bytes) Len() int
- func (b *Bytes) Partition(sep []byte) (*Bytes, *Bytes, *Bytes, error)
- func (b *Bytes) RFind(sub []byte, start, end int) int
- func (b *Bytes) RIndex(sub []byte, start, end int) (int, error)
- func (b *Bytes) RJust(width int, fill byte) *Bytes
- func (b *Bytes) RPartition(sep []byte) (*Bytes, *Bytes, *Bytes, error)
- func (b *Bytes) RSplit(sep []byte, maxsplit int) ([]*Bytes, error)
- func (b *Bytes) RStrip(chars []byte) *Bytes
- func (b *Bytes) Replace(old, repl []byte, count int) *Bytes
- func (b *Bytes) Split(sep []byte, maxsplit int) ([]*Bytes, error)
- func (b *Bytes) SplitLines(keepends bool) []*Bytes
- func (b *Bytes) StartsWith(prefix []byte, start, end int) bool
- func (b *Bytes) String() string
- func (b *Bytes) Strip(chars []byte) *Bytes
- func (b *Bytes) Translate(table, deleteChars []byte) (*Bytes, error)
- func (b *Bytes) ZFill(width int) *Bytes
- type CFunction
- type CallIter
- type Capsule
- type Cell
- type ClassMethod
- type Code
- type CodeReplace
- type CompareOp
- type Complex
- type Coroutine
- type Dict
- func (d *Dict) Contains(key Object) (bool, error)
- func (d *Dict) ConvertToCombined()
- func (d *Dict) DelItem(key Object) error
- func (d *Dict) GetItem(key Object) (Object, error)
- func (d *Dict) IsSplit() bool
- func (d *Dict) ItemsView() Object
- func (d *Dict) Keys() []Object
- func (d *Dict) KeysView() Object
- func (d *Dict) Len() int
- func (d *Dict) SetItem(key, value Object) error
- func (d *Dict) ValuesView() Object
- type Enumerate
- type ExceptionInstance
- type File
- type Filter
- type Float
- type Frame
- func (f *Frame) Back() *Frame
- func (f *Frame) Builtins() Object
- func (f *Frame) Code() *Code
- func (f *Frame) Globals() Object
- func (f *Frame) Interp() InterpreterFrame
- func (f *Frame) Lasti() int
- func (f *Frame) Lineno() int
- func (f *Frame) SetTrace(fn Object)
- func (f *Frame) SetTraceLines(v bool)
- func (f *Frame) SetTraceOpcodes(v bool)
- func (f *Frame) Trace() Object
- func (f *Frame) TraceLines() bool
- func (f *Frame) TraceOpcodes() bool
- type Function
- type GenMsg
- type Generator
- type GetSetDescr
- type Header
- type Instance
- type Int
- type InterpreterFrame
- type LineEntry
- type List
- func (l *List) Append(v Object)
- func (l *List) Clear()
- func (l *List) Copy() *List
- func (l *List) Count(value Object) (int, error)
- func (l *List) Index(value Object, start, stop int) (int, error)
- func (l *List) Insert(where int, value Object)
- func (l *List) Item(i int) Object
- func (l *List) Len() int
- func (l *List) Pop(i int) (Object, error)
- func (l *List) Remove(value Object) error
- func (l *List) Reverse()
- func (l *List) SetSlice(start, stop int, values []Object)
- func (l *List) Sort(keyfunc Object, reverse bool) (retErr error)
- type Map
- type MappingMethods
- type MemberDescr
- type MemoryView
- type MethFlag
- type MethodDef
- type Module
- type Namespace
- type NumberMethods
- type Object
- func Call(callable Object, args *Tuple, kwargs *Dict) (Object, error)
- func CallNoArgs(callable Object) (Object, error)
- func CallObject(callable Object, args *Tuple) (Object, error)
- func CallOneArg(callable Object, arg Object) (Object, error)
- func CallPrepend(callable Object, obj Object, args *Tuple, kwargs *Dict) (Object, error)
- func Ellipsis() Object
- func False() Object
- func GenericGetAttr(o Object, name Object) (Object, error)
- func GetAttr(o Object, name Object) (Object, error)
- func GetItem(o, key Object) (Object, error)
- func InternFromString(s string) Object
- func Iter(o Object) (Object, error)
- func IterNext(o Object) (Object, error)
- func MakeTpCall(callable Object, args []Object, nargs int, keywords Object) (Object, error)
- func MappingGetItemString(o Object, key string) (Object, error)
- func MappingGetOptionalItem(o, key Object) (Object, bool, error)
- func MappingGetOptionalItemString(o Object, key string) (Object, bool, error)
- func NewBool(b bool) Object
- func NewStr(s string) Object
- func None() Object
- func NotImplemented() Object
- func NumberAbsolute(o Object) (Object, error)
- func NumberAdd(a, b Object) (Object, error)
- func NumberAnd(a, b Object) (Object, error)
- func NumberDivmod(a, b Object) (Object, error)
- func NumberFloorDivide(a, b Object) (Object, error)
- func NumberInPlaceAdd(a, b Object) (Object, error)
- func NumberInPlaceAnd(a, b Object) (Object, error)
- func NumberInPlaceFloorDivide(a, b Object) (Object, error)
- func NumberInPlaceLshift(a, b Object) (Object, error)
- func NumberInPlaceMatrixMultiply(a, b Object) (Object, error)
- func NumberInPlaceMultiply(a, b Object) (Object, error)
- func NumberInPlaceOr(a, b Object) (Object, error)
- func NumberInPlacePower(a, b, mod Object) (Object, error)
- func NumberInPlaceRemainder(a, b Object) (Object, error)
- func NumberInPlaceRshift(a, b Object) (Object, error)
- func NumberInPlaceSubtract(a, b Object) (Object, error)
- func NumberInPlaceTrueDivide(a, b Object) (Object, error)
- func NumberInPlaceXor(a, b Object) (Object, error)
- func NumberIndex(o Object) (Object, error)
- func NumberInvert(o Object) (Object, error)
- func NumberLshift(a, b Object) (Object, error)
- func NumberMatrixMultiply(a, b Object) (Object, error)
- func NumberMultiply(a, b Object) (Object, error)
- func NumberNegative(o Object) (Object, error)
- func NumberOr(a, b Object) (Object, error)
- func NumberPositive(o Object) (Object, error)
- func NumberPower(a, b, mod Object) (Object, error)
- func NumberRemainder(a, b Object) (Object, error)
- func NumberRshift(a, b Object) (Object, error)
- func NumberSubtract(a, b Object) (Object, error)
- func NumberTrueDivide(a, b Object) (Object, error)
- func NumberXor(a, b Object) (Object, error)
- func RichCmp(a, b Object, op CompareOp) (Object, error)
- func SequenceConcat(s, o Object) (Object, error)
- func SequenceFast(v Object, m string) (Object, error)
- func SequenceGetItem(s Object, i int) (Object, error)
- func SequenceInPlaceConcat(s, o Object) (Object, error)
- func SequenceInPlaceRepeat(s Object, count int) (Object, error)
- func SequenceRepeat(s Object, count int) (Object, error)
- func True() Object
- func TypeOf(o Object) Object
- func Vectorcall(callable Object, args []Object, nargsf uint, kwnames *Tuple) (Object, error)
- func VectorcallDict(callable Object, args []Object, nargsf uint, kwargs *Dict) (Object, error)
- func VectorcallPrepend(callable Object, arg Object, args []Object, nargsf uint, kwnames *Tuple) (Object, error)
- type OrderedDict
- func (od *OrderedDict) Contains(key Object) (bool, error)
- func (od *OrderedDict) DelItem(key Object) error
- func (od *OrderedDict) GetItem(key Object) (Object, error)
- func (od *OrderedDict) Len() int
- func (od *OrderedDict) MoveToEnd(key Object, last bool) error
- func (od *OrderedDict) PopItem(last bool) (Object, Object, error)
- func (od *OrderedDict) SetItem(key, value Object) error
- type PositionEntry
- type Property
- type Range
- type Reversed
- type SeqIter
- type SequenceMethods
- type Set
- func (s *Set) Add(key Object) error
- func (s *Set) Contains(key Object) (bool, error)
- func (s *Set) Difference(others ...*Set) (*Set, error)
- func (s *Set) Discard(key Object) error
- func (s *Set) Intersection(others ...*Set) (*Set, error)
- func (s *Set) IsDisjoint(other *Set) (bool, error)
- func (s *Set) IsSubset(other *Set) (bool, error)
- func (s *Set) IsSuperset(other *Set) (bool, error)
- func (s *Set) Items() []Object
- func (s *Set) Len() int
- func (s *Set) SymmetricDifference(other *Set) (*Set, error)
- func (s *Set) Union(others ...*Set) (*Set, error)
- func (s *Set) Update(others ...*Set) error
- type SharedKeys
- type Slice
- type StaticMethod
- type StructSeq
- type StructSeqField
- type Super
- type Tuple
- type Type
- type Unicode
- type VarHeader
- type Visitor
- type WeakProxy
- type Weakref
Constants ¶
const ( StrKind1Byte byte = 1 StrKind2Byte byte = 2 StrKind4Byte byte = 4 )
PEP 393 kind values. Match CPython's PyUnicode_Kind enum.
CPython: Include/cpython/unicodeobject.h:L75 PyUnicode_Kind
const ( TpFlagMapping uint64 = 1 << 6 TpFlagSequence uint64 = 1 << 5 )
TpFlag values used by MATCH_MAPPING and MATCH_SEQUENCE.
CPython: Include/object.h:L284 Py_TPFLAGS_MAPPING / Py_TPFLAGS_SEQUENCE
const CoHasDocstring = 0x4000000
CoHasDocstring is the CO_HAS_DOCSTRING flag bit. When the bit is set on Code.Flags, co_consts[0] holds the function's docstring; NewFunctionWithQualName picks it up from there.
CPython: Include/cpython/code.h CO_HAS_DOCSTRING
const VectorcallArgumentsOffset uint = 1 << 63
VectorcallArgumentsOffset is the high bit of nargsf signaling that the caller reserved one slot at args[-1] for a self pointer; the callee may overwrite that slot. Mirrors PY_VECTORCALL_ARGUMENTS_OFFSET, the high bit of size_t.
CPython: Include/cpython/abstract.h:24 PY_VECTORCALL_ARGUMENTS_OFFSET
Variables ¶
var BoolType = NewType("bool", []*Type{IntType})
BoolType is the type singleton for bool. Mirrors PyBool_Type.
CPython: Objects/boolobject.c:L222 PyBool_Type
var BoundMethodType = NewType("method", []*Type{objectType})
BoundMethodType is the type singleton for bound methods.
CPython: Objects/classobject.c:268 PyMethod_Type
var BuiltinFunctionType = NewType("builtin_function_or_method", []*Type{objectType})
BuiltinFunctionType is the type singleton for built-in functions.
CPython: Objects/methodobject.c:357 PyCFunction_Type
var ByteArrayType = NewType("bytearray", []*Type{objectType})
ByteArrayType is the type singleton for bytearray.
CPython: Objects/bytearrayobject.c:2654 PyByteArray_Type
var BytesType = NewType("bytes", []*Type{objectType})
BytesType is the type singleton for bytes. Mirrors PyBytes_Type.
CPython: Objects/bytesobject.c:3134 PyBytes_Type
var CFunctionType = NewType("builtin_function_or_method", []*Type{objectType})
CFunctionType is the type singleton for CFunction. CPython uses PyCFunction_Type and a sibling PyCMethod_Type for MethMethod; gopy folds them into one type with a Cls field, since the dispatch difference is on the MethodDef flag set, not on the object layout.
CPython: Objects/methodobject.c:357 PyCFunction_Type
var CallIterType = NewType("callable_iterator", []*Type{objectType})
CallIterType is the type singleton for callable_iterator.
CPython: Objects/iterobject.c:171 PyCallIter_Type
var CapsuleType = NewType("PyCapsule", []*Type{objectType})
CapsuleType is the type singleton for capsules.
CPython: Objects/capsule.c:354 PyCapsule_Type
var CellType = NewType("cell", []*Type{objectType})
CellType is the type singleton for cell objects.
CPython: Objects/cellobject.c PyCell_Type
var ClassMethodType = NewType("classmethod", []*Type{objectType})
ClassMethodType is the type singleton for classmethod.
CPython: Objects/funcobject.c:1119 PyClassMethod_Type
var CodeType = NewType("code", []*Type{objectType})
CodeType is the type singleton for code objects.
CPython: Objects/codeobject.c:2980 PyCode_Type
var ComplexType = NewType("complex", []*Type{objectType})
ComplexType is the type singleton for complex.
CPython: Objects/complexobject.c:1075 PyComplex_Type
var DictType = NewType("dict", []*Type{objectType})
DictType is the type singleton for dict. Mirrors PyDict_Type.
CPython: Objects/dictobject.c:L4023 PyDict_Type
var EnumerateType = NewType("enumerate", []*Type{objectType})
EnumerateType is the type singleton for enumerate.
CPython: Python/bltinmodule.c:1455 PyEnum_Type
var ErrGeneratorExit = errors.New("GeneratorExit")
ErrGeneratorExit is the Go-level sentinel for PyExc_GeneratorExit. close() throws this into the body; if the body yields a value instead of swallowing it, the runtime raises RuntimeError per CPython's "generator ignored GeneratorExit" check.
CPython: Objects/exceptions.c PyExc_GeneratorExit
var ErrStopAsyncIteration = errors.New("StopAsyncIteration")
ErrStopAsyncIteration mirrors PyExc_StopAsyncIteration. An async generator returning normally surfaces this to its consumer.
CPython: Objects/exceptions.c PyExc_StopAsyncIteration
var ErrStopIteration = errors.New("StopIteration")
ErrStopIteration signals end of iteration. Mirrors PyExc_StopIteration.
CPython: Objects/exceptions.c:L1937 PyExc_StopIteration
var FileType = NewType("_io.File", []*Type{objectType})
FileType is the type singleton for File. CPython exposes three or four sibling types depending on mode; gopy's collapsed layer surfaces as the single name "_io.File".
CPython: Modules/_io/fileio.c:1245 PyFileIO_Type and friends
var FilterType = NewType("filter", []*Type{objectType})
FilterType is the type singleton for filter.
CPython: Python/bltinmodule.c:640 PyFilter_Type
var FloatType = NewType("float", []*Type{objectType})
FloatType is the type singleton for float. Mirrors PyFloat_Type. Slots are wired in init() because floatHash transitively constructs Ints which would otherwise close the dep cycle.
CPython: Objects/floatobject.c:L2068 PyFloat_Type
var FrozensetType = NewType("frozenset", []*Type{objectType})
FrozensetType is the type singleton for frozenset.
CPython: Objects/setobject.c:L2468 PyFrozenSet_Type
var FunctionType = NewType("function", []*Type{objectType})
FunctionType is the type singleton for Python-defined functions.
CPython: Objects/funcobject.c:1232 PyFunction_Type
var GetSetDescrType = NewType("getset_descriptor", []*Type{objectType})
GetSetDescrType is the type singleton for getset descriptors.
CPython: Objects/descrobject.c:1620 PyGetSetDescr_Type
var IntType = NewType("int", []*Type{objectType})
IntType is the type singleton for int. Mirrors PyLong_Type. Slots are wired in init() to break the variable-init dependency cycle (slots reference NewIntFromBig which references the small-int cache which references IntType).
CPython: Objects/longobject.c:L6447 PyLong_Type
var ListType = NewType("list", []*Type{objectType})
ListType is the type singleton for list. Mirrors PyList_Type.
CPython: Objects/listobject.c:L3380 PyList_Type
var MapType = NewType("map", []*Type{objectType})
MapType is the type singleton for map.
CPython: Python/bltinmodule.c:1624 PyMap_Type
var MemberDescrType = NewType("member_descriptor", []*Type{objectType})
MemberDescrType is the type singleton for __slots__ descriptors.
CPython: Objects/descrobject.c:1623 PyMemberDescr_Type
var MemoryViewType = NewType("memoryview", []*Type{objectType})
MemoryViewType is the type singleton for memoryview.
CPython: Objects/memoryobject.c:3402 PyMemoryView_Type
var ModuleType = NewType("module", []*Type{objectType})
ModuleType is the type singleton for module objects.
CPython: Objects/moduleobject.c:766 PyModule_Type
var NamespaceType = NewType("types.SimpleNamespace", []*Type{objectType})
NamespaceType is the type singleton for SimpleNamespace.
CPython: Objects/namespaceobject.c:275 _PyNamespace_Type
var OrderedDictType = NewType("OrderedDict", []*Type{DictType})
OrderedDictType is the type singleton for collections.OrderedDict.
CPython: Objects/odictobject.c:1840 PyODict_Type
var PropertyType = NewType("property", []*Type{objectType})
PropertyType is the type singleton for property.
CPython: Objects/descrobject.c:1817 PyProperty_Type
var RangeType = NewType("range", []*Type{objectType})
RangeType is the type singleton for range. Mirrors PyRange_Type.
CPython: Objects/rangeobject.c:L949 PyRange_Type
var ReversedType = NewType("reversed", []*Type{objectType})
ReversedType is the type singleton for reversed.
CPython: Python/bltinmodule.c:2724 PyReversed_Type
var SeqIterType = NewType("iterator", []*Type{objectType})
SeqIterType is the type singleton for seqiterator.
CPython: Objects/iterobject.c:21 PySeqIter_Type
var SetType = NewType("set", []*Type{objectType})
SetType is the type singleton for set.
CPython: Objects/setobject.c:L2318 PySet_Type
var SliceType = NewType("slice", []*Type{objectType})
SliceType is the type singleton for slice. Mirrors PySlice_Type.
CPython: Objects/sliceobject.c:L325 PySlice_Type
var StaticMethodType = NewType("staticmethod", []*Type{objectType})
StaticMethodType is the type singleton for staticmethod.
CPython: Objects/funcobject.c:1233 PyStaticMethod_Type
var SuperType = NewType("super", []*Type{objectType})
SuperType is the type singleton for the cooperative super helper.
CPython: Objects/typeobject.c:12313 PySuper_Type
var TupleType = NewType("tuple", []*Type{objectType})
TupleType is the type singleton for tuple. Mirrors PyTuple_Type.
CPython: Objects/tupleobject.c:L961 PyTuple_Type
var WeakCallableProxyType = NewType("weakcallableproxy", []*Type{objectType})
WeakCallableProxyType is the type singleton for weakref.CallableProxyType.
CPython: Objects/weakrefobject.c:887 _PyWeakref_CallableProxyType
var WeakProxyType = NewType("weakproxy", []*Type{objectType})
WeakProxyType is the type singleton for weakref.ProxyType.
CPython: Objects/weakrefobject.c:852 _PyWeakref_ProxyType
var WeakrefType = NewType("weakref", []*Type{objectType})
WeakrefType is the type singleton for weakref.ref.
CPython: Objects/weakrefobject.c:540 _PyWeakref_RefType
Functions ¶
func AdjustIndices ¶ added in v0.10.1
AdjustIndices clamps start/stop into [-1, length] (or [0, length]) depending on step direction and returns the resulting slice length.
CPython: Objects/sliceobject.c:264 PySlice_AdjustIndices
func ClearInterned ¶ added in v0.10.1
func ClearInterned()
ClearInterned drops every entry from the intern table. CPython runs this at interpreter shutdown to release the references it dropped when interning.
CPython: Objects/unicodeobject.c:16164 _PyUnicode_ClearInterned
func Contains ¶ added in v0.10.1
Contains reports whether v is in o. Routes through Sequence.Contains when present; otherwise falls back to a manual iterator walk.
CPython: Objects/abstract.c:2113 PySequence_Contains
func Decref ¶
func Decref(o Object)
Decref drops the refcount. If it reaches zero and the type defines a Dealloc slot, Dealloc is invoked. Until v0.10 lands the cycle collector, Dealloc is the only finalize hook.
CPython: Include/object.h:L631 Py_DECREF
func DelAttr ¶ added in v0.6.0
DelAttr deletes o.name. Forwards to SetAttr with value==nil to match CPython's single dispatch.
CPython: Objects/object.c:1490 PyObject_DelAttr
func DelItem ¶ added in v0.10.1
DelItem deletes o[key]. Forwards to SetItem with value==nil.
CPython: Objects/abstract.c:227 PyObject_DelItem
func Format ¶ added in v0.10.1
Format is the protocol-level entry point that ports PyObject_Format. An empty spec is shorthand for str(o); a non-empty spec dispatches to the type's Format slot, falling back to a TypeError for objects that don't define one.
CPython: Objects/object.c:L803 PyObject_Format
func GenericSetAttr ¶ added in v0.10.1
GenericSetAttr is the default Setattro slot. It looks up name in the type's MRO and calls DescrSet when the descriptor implements it, raising AttributeError otherwise. value==nil signals a delete and is passed through to DescrSet (descriptors handle the dispatch).
CPython: Objects/object.c:2040 PyObject_GenericSetAttr
func Hash ¶
Hash returns the hash of o. Errors with errUnhashable when the type has no Hash slot. Mirrors PyObject_Hash.
CPython: Objects/object.c:L869 PyObject_Hash
func HashBytes ¶ added in v0.10.1
HashBytes returns the hash of src using the active hash algorithm (SipHash-1-3 in CPython 3.14 default builds). The hash secret is supplied by the hash package; the -1 sentinel is remapped to -2 inside hash.Buffer so callers don't have to care.
CPython: Python/pyhash.c:148 Py_HashBuffer
func HashString ¶ added in v0.10.1
HashString is the string-shaped wrapper around HashBytes. Used by str so the slot implementation reads as "hash this string", not "convert to []byte and call the buffer hasher".
CPython: Objects/unicodeobject.c:11532 unicode_hash
func Incref ¶
func Incref(o Object)
Incref bumps the refcount. Concurrent Increfs are safe.
CPython: Include/object.h:L605 Py_INCREF
func IndexCheck ¶ added in v0.10.1
IndexCheck reports whether o exposes nb_index. Mirrors PyIndex_Check (which is _PyIndex_Check at the C level).
CPython: Objects/abstract.c:1387 PyIndex_Check
func InternInPlace ¶ added in v0.10.1
func InternInPlace(p *Object)
InternInPlace returns the canonical interned *Unicode for *p, rewriting *p so callers see the canonical pointer. Equivalent strings share the same *Unicode after this call. The pointer-to- interface signature is the contract CPython exposes; callers rely on the rewrite to swap in the canonical pointer.
CPython: Objects/unicodeobject.c:16135 PyUnicode_InternInPlace
func InternedCount ¶ added in v0.10.1
func InternedCount() int
InternedCount returns the number of interned strings. Used by tests; CPython exposes this via _PyUnicode_InternedSize.
CPython: Objects/unicodeobject.c:277 _PyUnicode_InternedSize
func Is ¶
Is reports identity equality, the Python `is` operator. Mirrors Py_Is.
CPython: Include/object.h:L257 Py_Is
func IsAlphaRune ¶ added in v0.10.1
IsAlphaRune reports whether r is a letter.
CPython: Objects/unicodectype.c:201 _PyUnicode_IsAlpha
func IsBool ¶ added in v0.10.1
IsBool reports whether o is True or False. Mirrors PyBool_Check.
CPython: Include/cpython/boolobject.h:11 PyBool_Check
func IsCasedRune ¶ added in v0.10.1
IsCasedRune reports whether r has any of upper/lower/title case.
CPython: Objects/unicodectype.c:142 _PyUnicode_IsCased
func IsDecimalRune ¶ added in v0.10.1
IsDecimalRune reports whether r has the Decimal_Digit property (the Nd category only).
CPython: Objects/unicodectype.c:213 _PyUnicode_IsDecimalDigit
func IsDigitRune ¶ added in v0.10.1
IsDigitRune reports whether r has the Digit property (Nd / No / Nl).
CPython: Objects/unicodectype.c:226 _PyUnicode_IsDigit
func IsEllipsis ¶ added in v0.10.1
IsEllipsis reports whether o is the Ellipsis singleton.
CPython: Objects/object.c Py_IsEllipsis (3.14+)
func IsFalse ¶ added in v0.10.1
IsFalse reports whether o is the False singleton (Python `o is False`).
CPython: Include/object.h:267 Py_IsFalse
func IsLowerRune ¶ added in v0.10.1
IsLowerRune reports whether r has the Lowercase property.
CPython: Objects/unicodectype.c:160 _PyUnicode_IsLowercase
func IsNone ¶
IsNone reports whether o is the None singleton. Mirrors Py_IsNone.
CPython: Include/object.h:L827 Py_IsNone
func IsNotImplemented ¶
IsNotImplemented reports whether o is the NotImplemented singleton.
CPython: Objects/object.c:L1965 Py_IsNotImplemented
func IsNumericRune ¶ added in v0.10.1
IsNumericRune reports whether r is in any Number category.
CPython: Objects/unicodectype.c:239 _PyUnicode_IsNumeric
func IsPrintableRune ¶ added in v0.10.1
IsPrintableRune reports whether r is printable. Matches CPython's definition: any rune that is not a control, format, surrogate, private-use, or unassigned code point. Space (U+0020) counts.
CPython: Objects/unicodectype.c:269 _PyUnicode_IsPrintable
func IsSpaceRune ¶ added in v0.10.1
IsSpaceRune reports whether r is whitespace.
CPython: Objects/unicodectype.c:252 _PyUnicode_IsWhitespace
func IsSubtype ¶
IsSubtype reports whether sub is sub or one of its bases. Mirrors PyType_IsSubtype.
CPython: Objects/typeobject.c:L2556 PyType_IsSubtype
func IsTitleRune ¶ added in v0.10.1
IsTitleRune reports whether r has the Titlecase property.
CPython: Objects/unicodectype.c:190 _PyUnicode_IsTitlecase
func IsTrue ¶ added in v0.10.1
IsTrue reports whether o is the True singleton (Python `o is True`).
CPython: Include/object.h:262 Py_IsTrue
func IsUpperRune ¶ added in v0.10.1
IsUpperRune reports whether r has the Uppercase property.
CPython: Objects/unicodectype.c:175 _PyUnicode_IsUppercase
func IsXIDContinueRune ¶ added in v0.10.1
IsXIDContinueRune reports whether r can continue an identifier.
CPython: Objects/unicodectype.c:294 _PyUnicode_IsXidContinue
func IsXIDStartRune ¶ added in v0.10.1
IsXIDStartRune reports whether r can begin an identifier.
CPython: Objects/unicodectype.c:283 _PyUnicode_IsXidStart
func Length ¶ added in v0.10.1
Length returns len(o). Routes through Mapping.Length first, then Sequence.Length, mirroring CPython's PyObject_Size dispatch.
CPython: Objects/abstract.c:55 PyObject_Size
func LookupDescriptor ¶ added in v0.10.1
LookupDescriptor walks t's MRO looking for an attribute named `name` that implements the descriptor protocol. Returns the descriptor object plus the type whose dict supplied it, or (nil, nil) when no descriptor is found. The instance attribute lookup machinery uses this to decide whether to call DescrGet.
CPython: Objects/typeobject.c:5121 _PyType_Lookup
func MakeStrTrans ¶ added in v0.10.1
MakeStrTrans builds a translation table from "from"/"to"/"delete" strings. from and to must be the same length; characters in delete map to -1.
CPython: Objects/unicodeobject.c:L13476 maketrans
func MappingCheck ¶ added in v0.10.1
MappingCheck reports whether o implements the mapping protocol. Mirrors the test CPython performs: mp_subscript must be wired.
CPython: Objects/abstract.c:2260 PyMapping_Check
func MappingDelItem ¶ added in v0.10.1
MappingDelItem removes o[key].
CPython: Objects/abstract.c PyMapping_DelItem (forwards to PyObject_DelItem)
func MappingDelItemString ¶ added in v0.10.1
MappingDelItemString removes o[key].
CPython: Objects/abstract.c PyMapping_DelItemString (forwards to PyObject_DelItem)
func MappingHasKey ¶ added in v0.10.1
MappingHasKey reports whether key is in o, swallowing any error (CPython logs the unraisable; gopy returns false). Use the WithError variant when callers need to surface failures.
CPython: Objects/abstract.c:2396 PyMapping_HasKey
func MappingHasKeyString ¶ added in v0.10.1
MappingHasKeyString is the string-key form.
CPython: Objects/abstract.c:2371 PyMapping_HasKeyString
func MappingHasKeyStringWithError ¶ added in v0.10.1
MappingHasKeyStringWithError is the string-key form.
CPython: Objects/abstract.c:2353 PyMapping_HasKeyStringWithError
func MappingHasKeyWithError ¶ added in v0.10.1
MappingHasKeyWithError reports whether key is in o, surfacing any non-KeyError as an actual error.
CPython: Objects/abstract.c:2362 PyMapping_HasKeyWithError
func MappingLength ¶ added in v0.10.1
MappingLength is the historical alias for MappingSize.
CPython: Objects/abstract.c:2292 PyMapping_Length
func MappingSetItemString ¶ added in v0.10.1
MappingSetItemString assigns o[key] = value where key is a Go string. value==nil signals delete (matches CPython routing through PyObject_SetItem with NULL).
CPython: Objects/abstract.c:2334 PyMapping_SetItemString
func MappingSize ¶ added in v0.10.1
MappingSize returns len(o) when o implements the mapping protocol. Falls through to a TypeError when o looks like a sequence instead, matching the message PySequence_Size uses to disambiguate.
CPython: Objects/abstract.c:2267 PyMapping_Size
func MissingArgumentsError ¶ added in v0.10.1
MissingArgumentsError formats the TypeError raised when one or more required parameters didn't get bound. kind is "positional" or "keyword-only"; names are the unbound parameter names in declared order.
CPython: Python/ceval.c:1448 missing_arguments / format_missing
func MultipleValuesForArgumentError ¶ added in v0.10.1
MultipleValuesForArgumentError is the TypeError raised when the same parameter is bound twice, once positionally and once by keyword.
CPython: Python/ceval.c (positional-already-set branch)
func PositionalOnlyAsKeywordError ¶ added in v0.10.1
PositionalOnlyAsKeywordError is the TypeError raised when caller keywords collide with positional-only parameter names.
CPython: Python/ceval.c:1546 positional_only_passed_as_keyword
func Repr ¶
Repr returns the Python repr of o. Falls back to a generic `<type at addr>` when the type lacks a Repr slot.
CPython: Objects/object.c:L518 PyObject_Repr
func RichCmpBool ¶
RichCmpBool runs RichCmp and converts the result to a Go bool. Mirrors PyObject_RichCompareBool.
CPython: Objects/object.c:L795 PyObject_RichCompareBool
func SequenceCheck ¶ added in v0.10.1
SequenceCheck reports whether s implements the sequence protocol. Dict is excluded because it advertises tp_as_sequence indirectly via the mapping protocol.
CPython: Objects/abstract.c:1672 PySequence_Check
func SequenceContains ¶ added in v0.10.1
SequenceContains reports whether o appears in s. Uses sq_contains when available, otherwise iterates.
CPython: Objects/abstract.c:2231 PySequence_Contains
func SequenceCount ¶ added in v0.10.1
SequenceCount returns the number of times o equals an element of s. Walks the iterator and compares with RichCmpBool, matching _PySequence_IterSearch in PY_ITERSEARCH_COUNT mode.
CPython: Objects/abstract.c:2222 PySequence_Count
func SequenceDelItem ¶ added in v0.10.1
SequenceDelItem is del s[i] on the sequence protocol; forwards to SequenceSetItem with v==nil.
CPython: Objects/abstract.c:1917 PySequence_DelItem
func SequenceIndex ¶ added in v0.10.1
SequenceIndex returns the position of the first element of s equal to o. Raises ValueError when o is absent.
CPython: Objects/abstract.c:2252 PySequence_Index
func SequenceSetItem ¶ added in v0.10.1
SequenceSetItem is s[i] = v on the sequence protocol.
CPython: Objects/abstract.c:1884 PySequence_SetItem
func SequenceSize ¶ added in v0.10.1
SequenceSize returns len(s) when s implements the sequence protocol. Returns a TypeError when s is a mapping or has no length slot, which is the same shape PySequence_Size reports.
CPython: Objects/abstract.c:1681 PySequence_Size
func SetAttr ¶ added in v0.6.0
SetAttr writes o.name = value. value==nil deletes the attribute (CPython routes PyObject_DelAttr through here too).
CPython: Objects/object.c:1440 PyObject_SetAttr
func SetItem ¶ added in v0.10.1
SetItem assigns o[key] = value. value==nil signals delete (DelItem forwards through here).
CPython: Objects/abstract.c:200 PyObject_SetItem
func SetTypeDescr ¶ added in v0.10.1
SetTypeDescr installs d as the attribute name on t. Used by built-in type initialisers to expose properties before the typeobject port gives every type a real __dict__.
CPython: Objects/typeobject.c:6012 type_add_method
func Str ¶
Str returns the Python str of o. Falls back to Repr.
CPython: Objects/object.c:L463 PyObject_Str
func StrCapitalize ¶ added in v0.10.1
StrCapitalize ports str.capitalize: first character upper, rest lower. Empty string is unchanged.
CPython: Objects/unicodeobject.c:L11107 unicode_capitalize_impl
func StrCaseFold ¶ added in v0.10.1
StrCaseFold approximates str.casefold via lowercasing.
CPython: Objects/unicodeobject.c:L11122 unicode_casefold_impl
func StrCenter ¶ added in v0.10.1
StrCenter / StrLJust / StrRJust pad to width with fillchar.
CPython: Objects/unicodeobject.c:L11166 unicode_center_impl CPython: Objects/unicodeobject.c:L12549 unicode_ljust_impl CPython: Objects/unicodeobject.c:L13085 unicode_rjust_impl
func StrCount ¶ added in v0.10.1
StrCount ports str.count: non-overlapping occurrences. Empty needle returns rune-count + 1.
CPython: Objects/unicodeobject.c:L11771 unicode_count_impl
func StrEndsWith ¶ added in v0.10.1
StrEndsWith ports str.endswith.
CPython: Objects/unicodeobject.c:L13665 unicode_endswith_impl
func StrExpandTabs ¶ added in v0.10.1
StrExpandTabs replaces tab characters with spaces such that columns align to the next multiple of tabsize.
CPython: Objects/unicodeobject.c:L11871 unicode_expandtabs_impl
func StrFind ¶ added in v0.10.1
StrFind ports str.find: leftmost index of needle in s[start:end] in code-point units, or -1 if not found.
CPython: Objects/unicodeobject.c:L11956 unicode_find_impl
func StrIndex ¶ added in v0.10.1
StrIndex is StrFind that raises ValueError on miss.
CPython: Objects/unicodeobject.c:L12019 unicode_index_impl
func StrIsASCII ¶ added in v0.10.1
func StrIsAlnum ¶ added in v0.10.1
func StrIsAlpha ¶ added in v0.10.1
func StrIsDecimal ¶ added in v0.10.1
func StrIsDigit ¶ added in v0.10.1
func StrIsIdentifier ¶ added in v0.10.1
func StrIsLower ¶ added in v0.10.1
func StrIsNumeric ¶ added in v0.10.1
func StrIsPrintable ¶ added in v0.10.1
func StrIsSpace ¶ added in v0.10.1
func StrIsTitle ¶ added in v0.10.1
func StrIsUpper ¶ added in v0.10.1
func StrJoin ¶ added in v0.10.1
StrJoin ports str.join. Each iterable item must be a *Unicode.
CPython: Objects/unicodeobject.c:L12524 unicode_join
func StrLStrip ¶ added in v0.10.1
StrLStrip ports str.lstrip.
CPython: Objects/unicodeobject.c:L12717 unicode_lstrip_impl
func StrLower ¶ added in v0.10.1
Case operations. Go's strings package routes through unicode case mappings, which match CPython for the vast majority of inputs. Edge cases like the Greek final-sigma in lower() are subtly different and tracked in 1677-D.
CPython: Objects/unicodeobject.c:L12559 unicode_lower_impl CPython: Objects/unicodeobject.c:L11042 unicode_upper_impl
func StrPartition ¶ added in v0.10.1
StrPartition ports str.partition.
CPython: Objects/unicodeobject.c:L13272 unicode_partition
func StrRFind ¶ added in v0.10.1
StrRFind ports str.rfind: rightmost index of needle.
CPython: Objects/unicodeobject.c:L13048 unicode_rfind_impl
func StrRIndex ¶ added in v0.10.1
StrRIndex is StrRFind that raises ValueError on miss.
CPython: Objects/unicodeobject.c:L13069 unicode_rindex_impl
func StrRPartition ¶ added in v0.10.1
StrRPartition ports str.rpartition.
CPython: Objects/unicodeobject.c:L13287 unicode_rpartition
func StrRSplit ¶ added in v0.10.1
StrRSplit ports str.rsplit.
CPython: Objects/unicodeobject.c:L13190 unicode_rsplit_impl
func StrRStrip ¶ added in v0.10.1
StrRStrip ports str.rstrip.
CPython: Objects/unicodeobject.c:L12737 unicode_rstrip_impl
func StrReplace ¶ added in v0.10.1
StrReplace ports str.replace. count<0 means all.
CPython: Objects/unicodeobject.c:L12885 unicode_replace_impl
func StrSplit ¶ added in v0.10.1
StrSplit ports str.split. sep="" means whitespace mode (CPython signals this with sep=None).
CPython: Objects/unicodeobject.c:L13138 unicode_split_impl
func StrSplitLines ¶ added in v0.10.1
StrSplitLines ports str.splitlines: line-terminator-aware split. CPython recognizes \r, \n, \r\n, plus the wider universal-newline set (\v, \f, \x1c..\x1e, \x85, , ).
CPython: Objects/unicodeobject.c:L13342 unicode_splitlines_impl CPython: Objects/stringlib/split.h:L243 stringlib_splitlines
func StrStartsWith ¶ added in v0.10.1
StrStartsWith ports str.startswith.
CPython: Objects/unicodeobject.c:L13609 unicode_startswith_impl
func StrStrip ¶ added in v0.10.1
StrStrip ports str.strip. chars="" means default whitespace.
CPython: Objects/unicodeobject.c:L12757 unicode_strip_impl
func StrSwapCase ¶ added in v0.10.1
StrSwapCase swaps each character's case.
CPython: Objects/unicodeobject.c:L11130 unicode_swapcase_impl
func StrTitle ¶ added in v0.10.1
StrTitle ports str.title: first character of each word uppercased, the rest lowercased. Word boundaries are runs of cased characters.
CPython: Objects/unicodeobject.c:L11091 unicode_title_impl
func StrTranslate ¶ added in v0.10.1
StrTranslate maps each rune via table[rune]. Missing entries pass through; entries whose value is -1 are deleted.
CPython: Objects/unicodeobject.c:L11231 unicode_translate
func StrZFill ¶ added in v0.10.1
StrZFill pads with leading zeros, preserving an optional +/- sign.
CPython: Objects/unicodeobject.c:L13110 unicode_zfill_impl
func ToLowerRune ¶ added in v0.10.1
ToLowerRune folds r to lowercase.
CPython: Objects/unicodectype.c:65 _PyUnicode_ToLowercase
func ToTitleRune ¶ added in v0.10.1
ToTitleRune folds r to titlecase.
CPython: Objects/unicodectype.c:117 _PyUnicode_ToTitlecase
func ToUpperRune ¶ added in v0.10.1
ToUpperRune folds r to uppercase.
CPython: Objects/unicodectype.c:91 _PyUnicode_ToUppercase
func TooManyPositionalError ¶ added in v0.10.1
TooManyPositionalError formats the TypeError raised when *args supplies more positional values than the signature accepts (and the function has no *args bucket). atLeast equals max minus the number of positional defaults; pass max twice for the no-default case. kwonlyGiven counts already-bound keyword-only parameters and triggers the parenthetical "(and N keyword-only argument)" tail.
CPython: Python/ceval.c:1487 too_many_positional
func UnexpectedKeywordError ¶ added in v0.10.1
UnexpectedKeywordError is the TypeError raised when a caller passes a keyword the signature doesn't declare (and there's no **kwargs).
CPython: Python/ceval.c (kwonly mismatch branch) + Objects/call.c
func UnpackKwargs ¶ added in v0.10.1
UnpackKwargs unpacks a *Dict of keyword arguments into the (kwnames, values) layout the vectorcall slot expects: kwnames is a tuple of name objects and values lines up positionally with it. All keys must be string objects; otherwise TypeError "keywords must be strings" is returned.
CPython: Objects/call.c:1038 _PyStack_UnpackDict
func VectorcallNargs ¶ added in v0.6.0
VectorcallNargs strips the VectorcallArgumentsOffset flag from nargsf and returns just the positional count.
CPython: Objects/call.c:1127 PyVectorcall_NARGS
Types ¶
type AsyncGenerator ¶ added in v0.10.1
type AsyncGenerator struct {
Header
Name string
YieldCh chan GenMsg
SendCh chan GenMsg
// contains filtered or unexported fields
}
AsyncGenerator mirrors PyAsyncGenObject.
CPython: Objects/genobject.c:L1577 PyAsyncGen_Type
func NewAsyncGenerator ¶ added in v0.10.1
func NewAsyncGenerator(name string) *AsyncGenerator
NewAsyncGenerator creates an async generator with the given name. The vm is responsible for spawning the body goroutine.
CPython: Objects/genobject.c:L1546 async_gen_new
func (*AsyncGenerator) Aclose ¶ added in v0.10.1
func (g *AsyncGenerator) Aclose() Object
Aclose returns an awaitable that drives Close.
CPython: Objects/genobject.c:L2317 async_gen_aclose
func (*AsyncGenerator) Anext ¶ added in v0.10.1
func (g *AsyncGenerator) Anext() Object
Anext is __anext__: shorthand for asend(None).
CPython: Objects/genobject.c:L1862 async_gen_anext
func (*AsyncGenerator) Asend ¶ added in v0.10.1
func (g *AsyncGenerator) Asend(v Object) Object
Asend returns an awaitable that, when driven, sends v into the async generator and yields the next value or raises StopAsyncIteration.
CPython: Objects/genobject.c:L1879 async_gen_asend
func (*AsyncGenerator) Athrow ¶ added in v0.10.1
func (g *AsyncGenerator) Athrow(err error) Object
Athrow returns an awaitable that throws err into the async generator and yields the result.
CPython: Objects/genobject.c:L2272 async_gen_athrow
func (*AsyncGenerator) Close ¶ added in v0.10.1
func (g *AsyncGenerator) Close() error
Close throws GeneratorExit. The "async generator ignored GeneratorExit" diagnostic mirrors CPython's check.
CPython: Objects/genobject.c gen_close async path
func (*AsyncGenerator) Send ¶ added in v0.10.1
func (g *AsyncGenerator) Send(v Object) (Object, error)
Send drives the async generator one yield-point forward. The public surface is asend(), which returns an awaitable; this method is the inner driver the awaitable uses.
CPython: Objects/genobject.c:L1879 async_gen_asend
type AsyncMethods ¶ added in v0.10.1
type AsyncMethods struct {
Aiter func(o Object) (Object, error)
Anext func(o Object) (Object, error)
Await func(o Object) (Object, error)
}
AsyncMethods mirrors PyAsyncMethods (tp_as_async). am_aiter returns the async iterator, am_anext returns the awaitable that yields the next value, am_await is the __await__ slot used by `await` itself.
CPython: Include/cpython/object.h PyAsyncMethods
type Bool ¶
type Bool struct {
Int
}
Bool is the Python bool. CPython makes bool a subclass of int with just two singleton instances; gopy follows the same pattern.
CPython: Objects/boolobject.c:L24 PyBool_Type
type BoundMethod ¶ added in v0.10.1
type BoundMethod struct {
Header
// contains filtered or unexported fields
}
BoundMethod is the value attribute access produces when a function is fetched off an instance: it pairs the function with the instance so calling it prepends the instance to the positional args.
CPython: Include/cpython/classobject.h:7 PyMethodObject
func NewBoundMethod ¶ added in v0.10.1
func NewBoundMethod(fn Object, self Object) *BoundMethod
NewBoundMethod pairs fn with self.
CPython: Objects/classobject.c:38 PyMethod_New
func (*BoundMethod) Func ¶ added in v0.10.1
func (m *BoundMethod) Func() Object
Func returns the underlying function.
func (*BoundMethod) Self ¶ added in v0.10.1
func (m *BoundMethod) Self() Object
Self returns the bound instance.
type BuiltinFunction ¶ added in v0.6.0
type BuiltinFunction struct {
Header
Name string
Fn func(args []Object, kwargs map[string]Object) (Object, error)
}
BuiltinFunction wraps a Go function so the VM can call it through the type's Vectorcall / Call slots. The Fn closure shape mirrors METH_VARARGS|METH_KEYWORDS (positional slice plus a kwargs map), which is the convention CPython's cfunction_call dispatches when vectorcall is unavailable.
CPython: Include/cpython/methodobject.h PyCFunctionObject
func NewBuiltinFunction ¶ added in v0.6.0
func NewBuiltinFunction(name string, fn func(args []Object, kwargs map[string]Object) (Object, error)) *BuiltinFunction
NewBuiltinFunction wraps fn under name.
type ByteArray ¶ added in v0.10.1
type ByteArray struct {
VarHeader
// contains filtered or unexported fields
}
ByteArray is the mutable byte string. Mirrors PyByteArrayObject.
CPython: Include/cpython/bytearrayobject.h:13 PyByteArrayObject
func NewByteArray ¶ added in v0.10.1
NewByteArray wraps a copy of buf in a ByteArray.
CPython: Objects/bytearrayobject.c:138 PyByteArray_FromStringAndSize
func (*ByteArray) Append ¶ added in v0.10.1
Append puts byte v at the tail. v must be in [0, 255].
CPython: Objects/bytearrayobject.c:2243 bytearray_append
func (*ByteArray) Bytes ¶ added in v0.10.1
Bytes returns the underlying mutable buffer. Callers may mutate the returned slice; doing so updates the ByteArray in place.
func (*ByteArray) Clear ¶ added in v0.10.1
func (b *ByteArray) Clear()
Clear truncates the buffer to zero length.
CPython: Objects/bytearrayobject.c:2191 bytearray_clear
func (*ByteArray) Extend ¶ added in v0.10.1
Extend concatenates the bytes from src.
CPython: Objects/bytearrayobject.c:2299 bytearray_extend
func (*ByteArray) Insert ¶ added in v0.10.1
Insert places v at position where, shifting later bytes right. Negative where is clamped to 0; where past the end appends.
CPython: Objects/bytearrayobject.c:2206 bytearray_insert
func (*ByteArray) Len ¶ added in v0.10.1
Len returns the number of bytes.
CPython: Objects/bytearrayobject.c:62 PyByteArray_Size
type Bytes ¶ added in v0.10.1
type Bytes struct {
VarHeader
// contains filtered or unexported fields
}
Bytes is the immutable byte string. Mirrors PyBytesObject.
CPython: Include/cpython/bytesobject.h:7 PyBytesObject
func BytesFromHex ¶ added in v0.10.1
BytesFromHex parses a hex string into a fresh bytes object. Whitespace between digit pairs is allowed (CPython documents this as "spaces between two numbers are accepted").
CPython: Objects/bytesobject.c:2503 bytes_fromhex_impl CPython: Objects/bytesobject.c:2513 _PyBytes_FromHex
func EmptyBytes ¶ added in v0.10.1
func EmptyBytes() *Bytes
EmptyBytes returns the empty bytes singleton (Python b"").
CPython: Objects/bytesobject.c:38 nullstring
func MakeBytesTrans ¶ added in v0.10.1
MakeBytesTrans builds a 256-byte translation table mapping frm[i] to to[i] for each i. Both must have the same length; CPython raises ValueError otherwise.
CPython: Objects/bytes_methods.c:_Py_bytes_maketrans
func NewBytes ¶ added in v0.10.1
NewBytes wraps a copy of buf in a Bytes object. An empty buf returns the cached singleton.
CPython: Objects/bytesobject.c:120 PyBytes_FromStringAndSize
func NewBytesFromString ¶ added in v0.10.1
NewBytesFromString wraps the bytes of s. CPython exposes this as PyBytes_FromString; the input is a NUL-terminated C string there but the gopy port takes a Go string and uses its full length.
CPython: Objects/bytesobject.c:159 PyBytes_FromString
func (*Bytes) Bytes ¶ added in v0.10.1
Bytes returns the underlying byte payload. The slice is shared with the object; callers must not mutate it.
func (*Bytes) Center ¶ added in v0.10.1
Center returns b padded to width with fill on both sides. Extra padding when the gap is odd lands on the right, matching CPython.
CPython: Objects/stringlib/transmogrify.h:174 stringlib_center
func (*Bytes) Count ¶ added in v0.10.1
Count returns the number of non-overlapping occurrences of sub in b[start:end]. The empty-needle case is len(slice)+1, matching both CPython and Go's bytes.Count.
CPython: Objects/bytesobject.c:2131 bytes_count_impl
func (*Bytes) EndsWith ¶ added in v0.10.1
EndsWith reports whether b[start:end] ends with suffix.
CPython: Objects/bytesobject.c:2434 bytes_endswith_impl
func (*Bytes) ExpandTabs ¶ added in v0.10.1
ExpandTabs replaces tabs with enough spaces to advance to the next multiple of tabsize, counting from the start of the current line. tabsize <= 0 just removes tabs.
CPython: Objects/stringlib/transmogrify.h:62 stringlib_expandtabs
func (*Bytes) Find ¶ added in v0.10.1
Find returns the lowest index in b where sub is found within b[start:end], or -1 when not present. Matches bytes.find.
CPython: Objects/bytesobject.c:1931 bytes_find_impl
func (*Bytes) Hex ¶ added in v0.10.1
Hex returns the hexadecimal representation of b. With sep != 0 the runs of bytesPerSep bytes are joined by sep; positive bytesPerSep counts from the right, negative from the left. bytesPerSep == 0 or sep == 0 means "no separator" (the simple b.hex() default).
CPython: Objects/bytesobject.c:2647 bytes_hex_impl CPython: Python/pystrhex.c _Py_strhex_with_sep
func (*Bytes) Index ¶ added in v0.10.1
Index is Find but raises ValueError when the substring is missing.
CPython: Objects/bytesobject.c:1990 bytes_index_impl
func (*Bytes) Join ¶ added in v0.10.1
Join concatenates the items of seq with b as the separator. Every item must be bytes-like; CPython raises TypeError on the first other type and includes the item index in the message.
CPython: Objects/bytesobject.c:1892 bytes_join_impl CPython: Objects/stringlib/join.h:13 stringlib_bytes_join
func (*Bytes) LJust ¶ added in v0.10.1
LJust pads on the right.
CPython: Objects/stringlib/transmogrify.h:139 stringlib_ljust
func (*Bytes) LStrip ¶ added in v0.10.1
LStrip strips only the leading run.
CPython: Objects/bytesobject.c:2099 bytes_lstrip_impl
func (*Bytes) Len ¶ added in v0.10.1
Len returns the number of bytes.
CPython: Objects/bytesobject.c:1228 PyBytes_Size
func (*Bytes) Partition ¶ added in v0.10.1
Partition cuts b at the first occurrence of sep into (head, sep, tail). When sep doesn't occur, the result is (b, b”, b”). An empty sep is a ValueError.
CPython: Objects/bytesobject.c:1807 bytes_partition_impl CPython: Objects/stringlib/partition.h:13 stringlib_partition
func (*Bytes) RFind ¶ added in v0.10.1
RFind returns the highest index in b where sub starts, or -1.
CPython: Objects/bytesobject.c:1969 bytes_rfind_impl
func (*Bytes) RIndex ¶ added in v0.10.1
RIndex is RFind but raises ValueError when the substring is missing.
CPython: Objects/bytesobject.c:2009 bytes_rindex_impl
func (*Bytes) RJust ¶ added in v0.10.1
RJust pads on the left.
CPython: Objects/stringlib/transmogrify.h:155 stringlib_rjust
func (*Bytes) RPartition ¶ added in v0.10.1
RPartition is Partition that searches from the right. The miss case mirrors CPython: (b”, b”, b) instead of (b, b”, b”).
CPython: Objects/bytesobject.c:1834 bytes_rpartition_impl CPython: Objects/stringlib/partition.h:55 stringlib_rpartition
func (*Bytes) RSplit ¶ added in v0.10.1
RSplit is Split that walks from the end. It only differs from Split when maxsplit is positive: the rightmost cuts are kept.
CPython: Objects/bytesobject.c:1853 bytes_rsplit_impl CPython: Objects/stringlib/split.h:154 stringlib_rsplit
func (*Bytes) RStrip ¶ added in v0.10.1
RStrip strips only the trailing run.
CPython: Objects/bytesobject.c:2117 bytes_rstrip_impl
func (*Bytes) Replace ¶ added in v0.10.1
Replace returns a copy with at most count non-overlapping occurrences of old swapped for new. count<0 means replace all.
CPython: Objects/bytesobject.c:2310 bytes_replace_impl CPython: Objects/stringlib/transmogrify.h:444 stringlib_replace
func (*Bytes) Split ¶ added in v0.10.1
Split splits the bytes on sep, with at most maxsplit cuts. A nil sep falls back to the whitespace split: runs of ASCII space are the delimiter and empty leading/trailing fields are dropped, as in " a b ".split() == ["a", "b"]. maxsplit < 0 means unlimited.
CPython: Objects/bytesobject.c:1768 bytes_split_impl CPython: Objects/stringlib/split.h:60 stringlib_split (and
stringlib_split_whitespace)
func (*Bytes) SplitLines ¶ added in v0.10.1
SplitLines breaks b at \n, \r, or \r\n. With keepends=true the terminator is kept on the line; otherwise it's dropped. Mirrors bytes.splitlines, which only treats CR/LF as line breaks (the universal newline set str.splitlines uses is wider).
CPython: Objects/bytesobject.c:2480 bytes_splitlines_impl CPython: Objects/stringlib/split.h:343 stringlib_splitlines
func (*Bytes) StartsWith ¶ added in v0.10.1
StartsWith reports whether b[start:end] begins with prefix. CPython also accepts a tuple of prefixes; that variant is a follow-up.
CPython: Objects/bytesobject.c:2411 bytes_startswith_impl
func (*Bytes) String ¶ added in v0.10.1
String returns the payload as a Go string. Equivalent to the Python expression bytes_obj.decode('latin-1').
func (*Bytes) Strip ¶ added in v0.10.1
Strip removes leading and trailing bytes that match chars. A nil chars defaults to ASCII whitespace.
CPython: Objects/bytesobject.c:2081 bytes_strip_impl
type CFunction ¶ added in v0.10.1
CFunction wraps a MethodDef plus a bound self. Callers reach the underlying closure via the type's Vectorcall slot; legacy paths land in the tp_call slot which forwards the same way cfunction_call does in CPython.
CPython: Include/cpython/methodobject.h PyCFunctionObject
func NewCFunction ¶ added in v0.10.1
NewCFunction binds def to self; module and cls are optional. cls must be set when def carries MethMethod, and absent otherwise, matching the SystemError shape of PyCMethod_New.
CPython: Objects/methodobject.c:46 PyCMethod_New
type CallIter ¶ added in v0.10.1
type CallIter struct {
Header
// contains filtered or unexported fields
}
CallIter backs iter(callable, sentinel): it calls callable() and stops when the result equals sentinel.
CPython: Objects/iterobject.c:155 calliterobject
func NewCallIter ¶ added in v0.10.1
NewCallIter wraps callable+sentinel as iter(callable, sentinel).
CPython: Objects/iterobject.c:139 PyCallIter_New
type Capsule ¶ added in v0.10.1
type Capsule struct {
Header
// contains filtered or unexported fields
}
Capsule mirrors PyCapsule.
CPython: Include/cpython/objimpl.h:80 PyCapsule
func NewCapsule ¶ added in v0.10.1
NewCapsule creates a capsule wrapping pointer with the given name and optional destructor. Pointer must be non-nil; CPython rejects null pointers with ValueError.
CPython: Objects/capsule.c:60 PyCapsule_New
func (*Capsule) Context ¶ added in v0.10.1
Context returns the user-supplied context value.
CPython: Objects/capsule.c PyCapsule_GetContext
func (*Capsule) GetPointer ¶ added in v0.10.1
GetPointer returns the wrapped pointer, but only if name matches exactly. Mismatched names raise ValueError, just like CPython.
CPython: Objects/capsule.c:99 PyCapsule_GetPointer
func (*Capsule) IsValid ¶ added in v0.10.1
IsValid reports whether the capsule is non-empty and its name matches.
CPython: Objects/capsule.c:87 PyCapsule_IsValid
func (*Capsule) Name ¶ added in v0.10.1
Name returns the capsule's name.
CPython: Objects/capsule.c PyCapsule_GetName
func (*Capsule) SetContext ¶ added in v0.10.1
SetContext attaches an opaque context value to the capsule.
CPython: Objects/capsule.c PyCapsule_SetContext
type Cell ¶ added in v0.6.0
Cell holds a single Object reference shared between an enclosing function and its inner closures. MAKE_CELL allocates one, LOAD_DEREF / STORE_DEREF read and write Contents, and COPY_FREE_VARS hands the outer cells to the inner frame.
CPython: Include/cpython/cellobject.h PyCellObject
type ClassMethod ¶ added in v0.10.1
type ClassMethod struct {
Header
// contains filtered or unexported fields
}
ClassMethod is the descriptor that turns @classmethod-decorated functions into "type-bound" methods. The class is what gets prepended to the call rather than the instance.
CPython: Include/cpython/funcobject.h ClassMethod (analog)
func NewClassMethod ¶ added in v0.10.1
func NewClassMethod(fn Object) *ClassMethod
NewClassMethod wraps fn so attribute access binds it to the class rather than the instance.
CPython: Objects/funcobject.c:1059 cm_init
func (*ClassMethod) Func ¶ added in v0.10.1
func (cm *ClassMethod) Func() Object
Func returns the wrapped callable.
type Code ¶ added in v0.5.5
type Code struct {
Header
// Argument shape. CPython sets all four counts at compile time;
// the interpreter reads them when binding a CALL_FUNCTION.
Argcount int
PosonlyArgcount int
KwonlyArgcount int
Stacksize int
// Flags carries the CO_* bitset (CO_OPTIMIZED, CO_NEWLOCALS,
// CO_VARARGS, CO_VARKEYWORDS, CO_NESTED, CO_GENERATOR,
// CO_COROUTINE, CO_ASYNC_GENERATOR, etc.).
Flags int
// Code is the bytecode blob. Each instruction is a 16-bit
// (op, arg) pair; the interpreter dispatch loop walks it.
Code []byte
// Consts is the literal table the LOAD_CONST opcode indexes into.
Consts []any
// Names, Varnames, Freevars, Cellvars are name tables indexed
// by their respective LOAD_/STORE_ opcodes.
Names []string
Varnames []string
Freevars []string
Cellvars []string
// Filename, Name, Qualname mirror co_filename / co_name /
// co_qualname. The traceback renderer reads them.
Filename string
Name string
Qualname string
// Firstlineno is the source line of the first statement in
// the code; the linetable encodes deltas from this anchor.
Firstlineno int
// Linetable is the PEP 626 location table. Decoded via
// CoLines / CoPositions in code_tables.go.
Linetable []byte
// ExceptionTable is the compact try/except table the
// interpreter walks on RAISE_VARARGS / END_FINALLY.
ExceptionTable []byte
}
Code is the AST -> bytecode handoff value. Compile produces one of these per code-bearing node (module, function body, class body, comprehension).
CPython: Include/internal/pycore_code.h:115 _PyCodeObject
func NewCode ¶ added in v0.6.0
func NewCode() *Code
NewCode returns a Code with its header bound to CodeType.
type CodeReplace ¶ added in v0.10.1
type CodeReplace struct {
Argcount *int
PosonlyArgcount *int
KwonlyArgcount *int
Stacksize *int
Flags *int
Firstlineno *int
Code []byte
Consts []any
Names []string
Varnames []string
Freevars []string
Cellvars []string
Filename *string
Name *string
Qualname *string
Linetable []byte
ExceptionTable []byte
// SetCode / SetConsts / ... let callers explicitly install a nil
// or empty slice override. Without these the zero-length slice
// is indistinguishable from "no override" and would always fall
// through to the original.
SetCode bool
SetConsts bool
SetNames bool
SetVarnames bool
SetFreevars bool
SetCellvars bool
SetLinetable bool
SetExceptionTable bool
}
CodeReplace lists every field code.replace accepts in CPython. A nil pointer means "leave the field unchanged"; a non-nil pointer (or non-nil slice) installs the override. Mirrors the keyword-arg surface of code.replace and its sibling code.__replace__ method.
CPython: Objects/codeobject.c:2858 code_replace_impl
type CompareOp ¶
type CompareOp int
CompareOp identifies the six comparison operators Python exposes through __lt__/__le__/__eq__/__ne__/__gt__/__ge__. Numeric values match the C macros Py_LT..Py_GE so direct ports of slot implementations can pass the integer through.
CPython: Include/object.h:L375 Py_LT
type Complex ¶ added in v0.10.1
type Complex struct {
Header
// contains filtered or unexported fields
}
Complex is the Python complex number.
CPython: Include/cpython/complexobject.h:7 PyComplexObject
func NewComplex ¶ added in v0.10.1
NewComplex builds a complex from real and imaginary parts.
CPython: Objects/complexobject.c:138 PyComplex_FromDoubles
func (*Complex) Complex128 ¶ added in v0.10.1
func (c *Complex) Complex128() complex128
Complex128 returns the underlying value.
type Coroutine ¶ added in v0.10.1
type Coroutine struct {
Header
Name string
YieldCh chan GenMsg
SendCh chan GenMsg
// contains filtered or unexported fields
}
Coroutine mirrors PyCoroObject. Internally it shares the Generator's channel-based suspend/resume model.
CPython: Objects/genobject.c:L1271 PyCoro_Type
func NewCoroutine ¶ added in v0.10.1
NewCoroutine creates a coroutine. Like Generator the caller is responsible for spawning the goroutine that drives the body.
CPython: Objects/genobject.c:L1219 coro_new
func (*Coroutine) Await ¶ added in v0.10.1
Await returns the iterator that drives this coroutine. CPython returns a thin wrapper whose __next__ forwards to send(None).
CPython: Objects/genobject.c:L1486 coro_await
func (*Coroutine) Close ¶ added in v0.10.1
Close throws GeneratorExit. A coroutine that yields after seeing GeneratorExit raises RuntimeError, mirroring "coroutine ignored GeneratorExit".
CPython: Objects/genobject.c:L388 gen_close (coroutine variant)
type Dict ¶
type Dict struct {
Header
// contains filtered or unexported fields
}
Dict is the Python dict.
CPython: Include/cpython/dictobject.h:19 PyDictObject
func CoerceStarKwargs ¶ added in v0.10.1
CoerceStarKwargs takes the mapping feeding `f(**kwargs)` and produces a *Dict. Dicts pass through. Other mappings get copied via Keys/GetItem; non-string keys raise the canonical TypeError.
CPython: Python/bytecodes.c CALL_FUNCTION_EX (PyDict_Update path when kwargs is not exactly a dict).
func FrameFastToLocals ¶ added in v0.10.1
FrameFastToLocals returns a fresh dict that maps the frame's local names to their current values. The order matches CPython:
- fast locals (Code.Varnames)
- cell vars (Code.Cellvars)
- free vars (Code.Freevars)
Unbound slots (Null in the activation record) are skipped, matching CPython's "missing key" behavior. The returned dict is owned by the caller; mutating it does not write back to the frame.
CPython: Objects/frameobject.c:1430 PyFrame_FastToLocalsWithError
func NewDict ¶
func NewDict() *Dict
NewDict builds an empty dict.
CPython: Objects/dictobject.c:L765 PyDict_New
func NewSplitDict ¶ added in v0.10.1
func NewSplitDict(sk *SharedKeys) *Dict
NewSplitDict builds a fresh dict whose initial keys are the shared set, each mapped to None. The returned dict carries a back-reference to sk so the type machinery can detect it's in split mode and so SharedKeys.refs reflects how many instances point at it.
CPython: Objects/dictobject.c:897 new_dict_with_shared_keys
func (*Dict) Contains ¶
Contains reports whether key is in the dict.
CPython: Objects/dictobject.c:L2495 PyDict_Contains
func (*Dict) ConvertToCombined ¶ added in v0.10.1
func (d *Dict) ConvertToCombined()
ConvertToCombined releases the dict's reference to its shared keys and flips it to combined storage. Once converted there's no path back: the dict owns its keys table outright and SharedKeys.refs drops by one, so a deleted instance no longer shows up in the type-level shared count.
CPython: Objects/dictobject.c:2125 dictresize (the !DK_IS_SHARED branch after a split insert that escaped the shared key set)
func (*Dict) DelItem ¶
DelItem removes key. Mirrors PyDict_DelItem.
CPython: Objects/dictobject.c:2834 PyDict_DelItem
func (*Dict) GetItem ¶
GetItem looks up key. Returns errKeyNotFound when absent.
CPython: Objects/dictobject.c:L1925 PyDict_GetItemWithError
func (*Dict) IsSplit ¶ added in v0.10.1
IsSplit reports whether d is still in split-keys mode (i.e. it hasn't been converted to combined storage yet).
func (*Dict) ItemsView ¶ added in v0.10.1
ItemsView returns a dict_items view over d.
CPython: Objects/dictobject.c:6674 dict_items_impl
func (*Dict) Keys ¶ added in v0.6.0
Keys returns a snapshot of the live keys in insertion order. The returned slice is owned by the caller.
CPython: Objects/dictobject.c PyDict_Keys
func (*Dict) KeysView ¶ added in v0.10.1
KeysView returns a dict_keys view over d. The view stays bound to d, so subsequent mutations show through.
CPython: Objects/dictobject.c:6562 dict_keys_impl
func (*Dict) SetItem ¶
SetItem inserts or replaces key. Mirrors PyDict_SetItem.
CPython: Objects/dictobject.c:1985 PyDict_SetItem
func (*Dict) ValuesView ¶ added in v0.10.1
ValuesView returns a dict_values view over d.
CPython: Objects/dictobject.c:6764 dict_values_impl
type Enumerate ¶ added in v0.10.1
type Enumerate struct {
Header
// contains filtered or unexported fields
}
Enumerate backs enumerate(iterable, start=0). Index uses big.Int so it stays correct past 2**63 the way CPython's enumobject does.
CPython: Python/bltinmodule.c:1390 enumobject
type ExceptionInstance ¶ added in v0.10.1
ExceptionInstance is the structural interface a Python exception object satisfies so packages outside errors/ can read its type and args without importing errors and creating layering cycles. The canonical implementation is *errors.Exception.
CPython: Objects/exceptions.c:L34 BaseExceptionObject (the fields PyExc_*Object exposes through tp_getset)
type File ¶ added in v0.10.1
type File struct {
Header
// contains filtered or unexported fields
}
File mirrors the union of FileIO + the buffer + TextIOWrapper. The read/write side is decided at open time and does not change; mixing '+' modes wires both rd and wr at construction.
func NewFile ¶ added in v0.10.1
NewFile constructs a File around an already-opened *os.File. The (name, mode, binary) trio describes how the file was opened so the Python-visible attributes match. readable and writable wire up the buffered reader / writer; an updating mode passes both true.
CPython: Modules/_io/fileio.c:243 fileio_init (analog)
func (*File) Close ¶ added in v0.10.1
Close flushes the writer (if any) and releases the underlying file descriptor. Calling Close on an already-closed File is a no-op.
CPython: Modules/_io/fileio.c:432 fileio_close
func (*File) Flush ¶ added in v0.10.1
Flush pushes any buffered writes to the underlying file. Read-only files accept the call as a no-op (matches IOBase.flush).
CPython: Modules/_io/bufferedio.c:519 bufferedwriter_flush_unlocked
func (*File) Read ¶ added in v0.10.1
Read returns up to size bytes / characters; size<0 reads until EOF. Binary mode returns Bytes, text mode returns Unicode (decoded as UTF-8).
CPython: Modules/_io/fileio.c:706 fileio_read (raw layer) CPython: Modules/_io/textio.c:1804 textiowrapper_read (text layer)
func (*File) Readline ¶ added in v0.10.1
Readline returns one line including the terminating '\n'. size>=0 caps the read length. Returns an empty string / bytes at EOF.
CPython: Modules/_io/iobase.c:830 iobase_readline (driver)
func (*File) Write ¶ added in v0.10.1
Write pushes the source bytes / characters into the buffer. Returns the number of bytes written from the underlying buffer's perspective (matches CPython's _io._BufferedIOBase.write contract).
CPython: Modules/_io/fileio.c:887 fileio_write (raw layer) CPython: Modules/_io/textio.c:1499 textiowrapper_write (text layer)
type Filter ¶ added in v0.10.1
Filter is filterobject.
CPython: Python/bltinmodule.c:493 filterobject
type Float ¶
type Float struct {
Header
// contains filtered or unexported fields
}
Float is the Python float, an IEEE-754 double.
CPython: Include/cpython/floatobject.h:L7 PyFloatObject
func FloatFromString ¶ added in v0.10.1
FloatFromString parses a Python float literal. Whitespace on either side is ignored, sign and inf/nan tokens are recognized case-insensitively, and underscores are allowed between digits.
CPython: Objects/floatobject.c:172 PyFloat_FromString
type Frame ¶ added in v0.10.1
type Frame struct {
Header
// contains filtered or unexported fields
}
Frame is the Python-level frame object. It wraps an interpreter frame and adds per-frame trace settings (f_trace, f_trace_lines, f_trace_opcodes) that don't belong in the activation record.
CPython: Include/cpython/frameobject.h PyFrameObject
func NewFrame ¶ added in v0.10.1
func NewFrame(interp InterpreterFrame) *Frame
NewFrame wraps interp in a Python-level frame object. interp is the live activation record; the wrapper holds it as an interface so objects/ does not import frame/.
CPython: Objects/frameobject.c:1109 _PyFrame_New_NoTrack
func (*Frame) Back ¶ added in v0.10.1
Back returns the caller's Python-level frame. nil when this frame has no caller.
CPython: Objects/frameobject.c:1314 PyFrame_GetBack
func (*Frame) Builtins ¶ added in v0.10.1
Builtins returns f.f_builtins.
CPython: Objects/frameobject.c:888 frame_getbuiltins / 1346 PyFrame_GetBuiltins
func (*Frame) Code ¶ added in v0.10.1
Code returns f.f_code: the running Code object.
CPython: Objects/frameobject.c:794 frame_getcode / 1336 PyFrame_GetCode
func (*Frame) Globals ¶ added in v0.10.1
Globals returns f.f_globals.
CPython: Objects/frameobject.c:879 frame_getglobals / 1357 PyFrame_GetGlobals
func (*Frame) Interp ¶ added in v0.10.1
func (f *Frame) Interp() InterpreterFrame
Interp returns the underlying interpreter frame.
func (*Frame) Lasti ¶ added in v0.10.1
Lasti returns f.f_lasti, the offset (in code units) of the last dispatched instruction.
CPython: Objects/frameobject.c:802 frame_getlasti / 1380 PyFrame_GetLasti
func (*Frame) Lineno ¶ added in v0.10.1
Lineno returns f.f_lineno: the source line of the running instruction. Zero when the line table is empty or f_lasti falls outside any covered range.
CPython: Objects/frameobject.c:843 frame_getlineno / 1242 PyFrame_GetLineNumber
func (*Frame) SetTrace ¶ added in v0.10.1
SetTrace sets f.f_trace. Pass nil or None to clear.
CPython: Objects/frameobject.c:870 frame_settrace
func (*Frame) SetTraceLines ¶ added in v0.10.1
SetTraceLines stores f.f_trace_lines.
func (*Frame) SetTraceOpcodes ¶ added in v0.10.1
SetTraceOpcodes stores f.f_trace_opcodes.
func (*Frame) Trace ¶ added in v0.10.1
Trace returns f.f_trace, or None if no trace function is set.
CPython: Objects/frameobject.c:863 frame_gettrace
func (*Frame) TraceLines ¶ added in v0.10.1
TraceLines reports f.f_trace_lines.
func (*Frame) TraceOpcodes ¶ added in v0.10.1
TraceOpcodes reports f.f_trace_opcodes.
type Function ¶ added in v0.6.0
type Function struct {
Header
Name string
Qualname string
Code *Code
Globals Object // __globals__, typically *Dict
Builtins Object // __builtins__, loaded from globals['__builtins__']
Module Object // __module__, from globals['__name__'], may be nil
Doc Object // __doc__, from co_consts[0] when CoHasDocstring, else None
Defaults *Tuple // __defaults__, may be nil
KwDefaults *Dict // __kwdefaults__, may be nil
Closure *Tuple // __closure__, tuple of cells, may be nil
Annotations *Dict // __annotations__, may be nil
Annotate Object // __annotate__, callable that fills annotations on demand
Typeparams *Tuple // __type_params__, may be nil
Dict *Dict // __dict__, may be nil
// Version is the specializer key. Reset to zero whenever Code,
// Defaults, KwDefaults, Closure, or Annotations change. Specialized
// CALL guards check this against an inline cache; gopy doesn't run
// the specializer yet, but the field tracks the same invariants so
// callers can pin it later.
//
// CPython: Include/cpython/funcobject.h:55 func_version
Version uint32
}
Function represents a Python-defined function. The runtime call arm pushes a new frame off Code, threads Globals into the frame's f_globals, and dispatches.
CPython: Include/cpython/funcobject.h:36 PyFunctionObject
func NewFunction ¶ added in v0.6.0
NewFunction is the no-qualname form of NewFunctionWithQualName.
CPython: Objects/funcobject.c:407 PyFunction_New
func NewFunctionWithQualName ¶ added in v0.10.1
NewFunctionWithQualName builds a function from a code object and captured globals, picking the docstring out of co_consts[0] when CoHasDocstring is set, the module name from globals['__name__'], and the builtins dict from globals['__builtins__']. qualname=="" falls back to code.Qualname.
CPython: Objects/funcobject.c:148 PyFunction_NewWithQualName
func (*Function) GetAnnotations ¶ added in v0.10.1
GetAnnotations returns __annotations__, lazily materializing the dict from the Annotate callable on first access. Mirrors func_get_annotation_dict, which calls __annotate__(1) and caches the result.
CPython: Objects/funcobject.c:551 func_get_annotation_dict
func (*Function) SetAnnotations ¶ added in v0.10.1
SetAnnotations sets __annotations__ to d (nil clears it) and drops any pending Annotate callable. Does not zero Version since CPython treats annotations as a non-critical attribute for the specializer.
CPython: Objects/funcobject.c:607 PyFunction_SetAnnotations
func (*Function) SetClosure ¶ added in v0.10.1
SetClosure sets __closure__ to t (nil clears it) and zeros Version.
CPython: Objects/funcobject.c:528 PyFunction_SetClosure
func (*Function) SetCode ¶ added in v0.10.1
SetCode binds a new code object. Rejects code with a free-var count that doesn't match the captured closure size, mirroring func_set_code's nclosure==nfreevars guard.
CPython: Objects/funcobject.c:661 func_set_code
func (*Function) SetDefaults ¶ added in v0.10.1
SetDefaults sets __defaults__ to t (nil clears it) and zeros Version.
CPython: Objects/funcobject.c:453 PyFunction_SetDefaults
func (*Function) SetKwDefaults ¶ added in v0.10.1
SetKwDefaults sets __kwdefaults__ to d (nil clears it) and zeros Version.
CPython: Objects/funcobject.c:494 PyFunction_SetKwDefaults
type GenMsg ¶ added in v0.9.0
type GenMsg struct {
Val Object // yielded / sent value; nil when Err is set
Err error // ErrStopIteration at normal end; other errors on throw()
}
GenMsg is the channel message type for the generator yield/send protocol. Exported so the vm package can use it without importing this struct from a helper package.
type Generator ¶ added in v0.9.0
type Generator struct {
Header
Name string
// YieldCh carries values from the generator to the caller.
YieldCh chan GenMsg
// SendCh carries values from the caller into the generator.
SendCh chan GenMsg
// contains filtered or unexported fields
}
Generator is PyGenObject: a suspended frame that produces values one at a time via __next__ or send(). The goroutine that runs the generator body communicates through YieldCh and SendCh.
CPython: Objects/genobject.c:L49 PyGenObject
func NewGenerator ¶ added in v0.9.0
NewGenerator creates a generator with the given name. The caller (RETURN_GENERATOR in the vm package) is responsible for starting the goroutine that drives the body and communicates via YieldCh/SendCh.
CPython: Objects/genobject.c:L867 gen_new_with_qualname
func (*Generator) Close ¶ added in v0.9.0
Close throws GeneratorExit into the generator. A body that yields instead of swallowing the exit raises RuntimeError; StopIteration and GeneratorExit are both treated as a clean exit.
CPython: Objects/genobject.c:L388 gen_close
func (*Generator) Send ¶ added in v0.9.0
Send delivers v into the generator and returns the next yielded value. Sending None to an unstarted generator is equivalent to __next__. Sending a non-None to an unstarted generator raises TypeError.
CPython: Objects/genobject.c:L260 gen_send_ex2
type GetSetDescr ¶ added in v0.10.1
type GetSetDescr struct {
Header
// contains filtered or unexported fields
}
GetSetDescr is the v0.10 base descriptor: a (name, fget, fset) triple that exposes a Go-backed property to Python attribute lookup. CPython uses this exact shape for type-level data descriptors generated by PyDescr_NewGetSet.
CPython: Objects/descrobject.c:1620 PyGetSetDescr_Type
func NewGetSetDescr ¶ added in v0.10.1
func NewGetSetDescr(name string, fget func(owner Object) (Object, error), fset func(owner Object, value Object) error) *GetSetDescr
NewGetSetDescr builds a getset descriptor that exposes name on the host type. fget is required; fset may be nil for read-only descriptors (mirroring CPython's behavior of raising AttributeError on assignment when no setter is registered).
CPython: Objects/descrobject.c:1696 PyDescr_NewGetSet
func (*GetSetDescr) Name ¶ added in v0.10.1
func (d *GetSetDescr) Name() string
Name returns the attribute name this descriptor binds to.
type Header ¶
type Header struct {
// contains filtered or unexported fields
}
Header is the per-object header. Mirrors struct _object in cpython/Include/object.h. The zero value is invalid; constructors set refcount to 1 and install the type pointer.
CPython: Include/object.h:L107 _object
func (*Header) Init ¶ added in v0.3.0
Init is the cross-package entry point to init. Out-of-package types such as the exception in errors/ embed Header and need to bind their Header.typ to a *Type without re-implementing the refcount dance.
CPython: Objects/object.c:L184 _PyObject_Init
type Instance ¶ added in v0.10.1
type Instance struct {
Header
// contains filtered or unexported fields
}
Instance backs a Python-level object whose type is a user-defined class. Header.typ is the class; dict holds per-instance attributes (nil when the class declared __slots__ without __dict__); slots holds the fixed-index storage for __slots__ entries.
func NewInstance ¶ added in v0.10.1
NewInstance allocates a fresh Instance bound to t. The instance __dict__ is empty when t.HasDict; the slots array is sized to t.Slots and starts all-nil (each slot reads as AttributeError until assigned).
CPython: Objects/typeobject.c:1748 type_call (object_new path)
type Int ¶
type Int struct {
Header
// contains filtered or unexported fields
}
Int is the Python int. CPython stores arbitrary-precision integers as a sign + digit array on PyLong; gopy uses math/big.Int for the same semantics. The fast-path for machine-word ints lands in v0.4 alongside the longobject.c port proper.
CPython: Include/cpython/longintrepr.h:L11 _PyLongValue
func IntFromString ¶ added in v0.10.1
IntFromString mirrors PyLong_FromString. base==0 triggers prefix detection (0x, 0o, 0b, or decimal). Otherwise base must be in 2..36 and a matching prefix is allowed but optional.
CPython: Objects/longobject.c:2693 PyLong_FromString
func NewInt ¶
NewInt builds an int from an int64. Returns the cached singleton for the small-int range.
CPython: Objects/longobject.c:L322 PyLong_FromLong
func NewIntFromBig ¶
NewIntFromBig builds an int from a math/big.Int. Returns the cached singleton when the value fits the small-int window.
CPython: Objects/longobject.c:L156 _PyLong_FromBytes (adapted from)
type InterpreterFrame ¶ added in v0.10.1
type InterpreterFrame interface {
FrameCode() *Code
FrameGlobals() Object
FrameBuiltins() Object
FrameLocals() Object
FrameBack() InterpreterFrame
FrameLasti() int
FrameNumLocals() int
FrameFastLocal(i int) Object
FrameNumCells() int
FrameCellLocal(i int) Object
FrameNumFrees() int
FrameFreeLocal(i int) Object
}
InterpreterFrame is the read-only access objects.Frame needs from the interpreter-side activation record. Defining the contract here keeps the dependency arrow pointing the right way: frame depends on objects, and the live frame implements an interface objects owns.
Method names mirror CPython's PyFrame_Get* / PyFrame_FastLocal* helpers (with the Frame prefix kept to avoid collisions with the activation-record's own field names).
CPython: Include/cpython/frameobject.h PyFrame_GetCode / GetBack / GetGlobals / GetBuiltins / GetLasti
type LineEntry ¶ added in v0.5.5
LineEntry is one decoded line-table record. Start and End are bytecode byte offsets (half-open span); Line is the source line (1-based) or -1 when the entry has no associated source line.
CPython: Objects/codeobject.c:1156 PyCodeAddressRange (ar_start / ar_end / ar_line fields, projected without the column data).
type List ¶
type List struct {
VarHeader
// contains filtered or unexported fields
}
List is the Python list, a mutable ordered sequence.
CPython: Include/cpython/listobject.h:L7 PyListObject
func MappingItems ¶ added in v0.10.1
MappingItems returns list(o.items()) as a list of (key, value) 2-tuples. Dict uses the fast path; otherwise dispatches through `o.items()`.
CPython: Objects/abstract.c:2465 PyMapping_Items
func MappingKeys ¶ added in v0.10.1
MappingKeys returns list(o.keys()). Dict gets a fast path that reads its entry table directly; everything else dispatches through a `o.keys()` method call and materializes the result via SequenceList.
CPython: Objects/abstract.c:2453 PyMapping_Keys
func MappingValues ¶ added in v0.10.1
MappingValues returns list(o.values()).
CPython: Objects/abstract.c:2477 PyMapping_Values
func NewList ¶
NewList builds a list from items. The slice is copied.
CPython: Objects/listobject.c:L156 PyList_New
func SequenceList ¶ added in v0.10.1
SequenceList consumes v's iterator and returns a fresh list. The special-case PyList_CheckExact branch in CPython makes a copy of an existing list; gopy follows suit so callers don't accidentally alias the input.
CPython: Objects/abstract.c:2072 PySequence_List
func (*List) Append ¶
Append adds v to the end. Mirrors PyList_Append.
CPython: Objects/listobject.c:L351 PyList_Append
func (*List) Clear ¶ added in v0.10.1
func (l *List) Clear()
Clear empties the list.
CPython: Objects/listobject.c:1228 list_clear
func (*List) Copy ¶ added in v0.10.1
Copy returns a shallow copy.
CPython: Objects/listobject.c:1248 list_copy
func (*List) Count ¶ added in v0.10.1
Count returns the number of elements equal to value.
CPython: Objects/listobject.c:1502 list_count
func (*List) Index ¶ added in v0.10.1
Index returns the position of the first item equal to value inside [start, stop). Negative bounds are normalised the same way list_index_impl does, and a missing match raises ValueError.
CPython: Objects/listobject.c:1430 list_index_impl
func (*List) Insert ¶ added in v0.10.1
Insert puts value at position where, shifting later items right. Negative where is clamped to 0; where past the end appends.
CPython: Objects/listobject.c:1138 list_insert_impl
func (*List) Item ¶
Item returns the item at index i without bounds check.
CPython: Objects/listobject.c:L308 PyList_GetItem
func (*List) Pop ¶ added in v0.10.1
Pop removes and returns items[i]. i==-1 (the default at the call site) pops the tail. Out-of-range indices raise IndexError.
CPython: Objects/listobject.c:1365 list_pop_impl
func (*List) Remove ¶ added in v0.10.1
Remove deletes the first occurrence equal to value.
CPython: Objects/listobject.c:1408 list_remove
func (*List) Reverse ¶ added in v0.10.1
func (l *List) Reverse()
Reverse reverses items in place.
CPython: Objects/listobject.c:1262 list_reverse
func (*List) SetSlice ¶ added in v0.6.0
SetSlice replaces items[start:stop] with values. CPython implements this through PyList_SetSlice; the gopy port keeps the contract (start and stop already clamped/normalized by the caller).
CPython: Objects/listobject.c PyList_SetSlice
func (*List) Sort ¶ added in v0.10.1
Sort sorts l in place using Timsort+powersort. keyfunc may be nil (no key projection); reverse=true sorts descending while keeping stability by reversing the input, sorting forward, then reversing the output.
The list is "detached" by saving its items and resetting len to 0 for the duration of the sort: any callback that mutates the list during the comparison sees an empty list rather than corrupting the slice we're sorting under it. CPython uses the same trick to avoid core dumps from comparison-time mutation.
CPython: Objects/listobject.c:2900 list_sort_impl
type MappingMethods ¶
type MappingMethods struct {
Length func(o Object) (int, error)
GetItem func(o, key Object) (Object, error)
SetItem func(o, key, v Object) error
DelItem func(o, key Object) error
}
MappingMethods is the v0.2 subset of tp_as_mapping.
CPython: Include/cpython/object.h:L255 PyMappingMethods
type MemberDescr ¶ added in v0.10.1
type MemberDescr struct {
Header
// contains filtered or unexported fields
}
MemberDescr is a (name, slot index) pair exposed as a data descriptor on the type that declared it.
CPython: Objects/descrobject.c:1623 PyMemberDescr_Type
func NewMemberDescr ¶ added in v0.10.1
func NewMemberDescr(name string, index int) *MemberDescr
NewMemberDescr builds a slot descriptor for name backed by the slot at index in the instance slots array.
CPython: Objects/descrobject.c:1696 PyDescr_NewMember
func (*MemberDescr) Index ¶ added in v0.10.1
func (d *MemberDescr) Index() int
Index returns the slot index this descriptor reads/writes.
func (*MemberDescr) Name ¶ added in v0.10.1
func (d *MemberDescr) Name() string
Name returns the attribute name this descriptor binds to.
type MemoryView ¶ added in v0.10.1
type MemoryView struct {
Header
// contains filtered or unexported fields
}
MemoryView is a 1-D contiguous view over a byte buffer.
CPython: Objects/memoryobject.c:3402 PyMemoryView_Type
func NewMemoryView ¶ added in v0.10.1
func NewMemoryView(src Object) (*MemoryView, error)
NewMemoryView wraps src in a memoryview. The view aliases the underlying byte slice; callers can read but the readonly flag determines whether the type can later expose mutation. Bytes get a read-only view; bytearray is technically writable but v0.10 keeps every view read-only.
CPython: Objects/memoryobject.c:1041 PyMemoryView_FromObject
func (*MemoryView) Bytes ¶ added in v0.10.1
func (m *MemoryView) Bytes() []byte
Bytes returns the underlying byte slice. The slice is the live buffer, not a copy: matches CPython's PyMemoryView_GetContiguous for the trivial 1-D unsigned-byte case.
func (*MemoryView) Len ¶ added in v0.10.1
func (m *MemoryView) Len() int
Len reports the number of items (bytes, in the v0.10 port).
func (*MemoryView) Tobytes ¶ added in v0.10.1
func (m *MemoryView) Tobytes() *Bytes
Tobytes returns a fresh Bytes copy of the view.
CPython: Objects/memoryobject.c:2374 memoryview_tobytes_impl
func (*MemoryView) Tolist ¶ added in v0.10.1
func (m *MemoryView) Tolist() *List
Tolist returns the view as a list of int byte values.
CPython: Objects/memoryobject.c:2467 memoryview_tolist
type MethFlag ¶ added in v0.10.1
type MethFlag int
MethFlag is the bit field stored in MethodDef.Flags. Mirrors the METH_* constants in Include/methodobject.h: each value labels which closure the dispatcher should call and what argument shape it expects.
CPython: Include/methodobject.h:95 METH_VARARGS
type MethodDef ¶ added in v0.10.1
type MethodDef struct {
Name string
Doc string
Flags MethFlag
// MethNoArgs: f(self).
NoArgs func(self Object) (Object, error)
// MethO: f(self, arg).
O func(self, arg Object) (Object, error)
// MethVarargs: f(self, args).
Varargs func(self Object, args *Tuple) (Object, error)
// MethVarargs|MethKeywords: f(self, args, kwargs).
VarargsKw func(self Object, args *Tuple, kwargs *Dict) (Object, error)
// MethFastcall: f(self, args).
Fastcall func(self Object, args []Object) (Object, error)
// MethFastcall|MethKeywords: f(self, args, kwnames).
FastcallKw func(self Object, args []Object, kwnames *Tuple) (Object, error)
// MethMethod|MethFastcall|MethKeywords: f(self, cls, args, kwnames).
Method func(self Object, cls *Type, args []Object, kwnames *Tuple) (Object, error)
}
MethodDef is the gopy analog of PyMethodDef. The mask of Flags against the calling-convention bits picks which of the closures is consulted. Every variant is optional, but exactly one must be set for the chosen flag combo or NewCFunction returns SystemError the way PyCMethod_New does.
CPython: Include/methodobject.h:71 PyMethodDef
type Module ¶ added in v0.8.0
type Module struct {
Header
// contains filtered or unexported fields
}
Module mirrors PyModuleObject.
CPython: Include/cpython/moduleobject.h:11 PyModuleObject
func NewModule ¶ added in v0.8.0
NewModule creates an empty module with the given name in its __dict__.
CPython: Objects/moduleobject.c:74 PyModule_NewObject
func (*Module) Dict ¶ added in v0.8.0
Dict returns the module's attribute dict (__dict__).
CPython: Objects/moduleobject.c:459 PyModule_GetDict
type Namespace ¶ added in v0.10.1
type Namespace struct {
Header
// contains filtered or unexported fields
}
Namespace mirrors _PyNamespaceObject.
CPython: Objects/namespaceobject.c:11 _PyNamespaceObject
func NewNamespace ¶ added in v0.10.1
func NewNamespace() *Namespace
NewNamespace creates an empty SimpleNamespace.
CPython: Objects/namespaceobject.c:27 namespace_new
type NumberMethods ¶
type NumberMethods struct {
Add func(a, b Object) (Object, error)
Subtract func(a, b Object) (Object, error)
Multiply func(a, b Object) (Object, error)
MatrixMultiply func(a, b Object) (Object, error)
TrueDivide func(a, b Object) (Object, error)
FloorDivide func(a, b Object) (Object, error)
Remainder func(a, b Object) (Object, error)
And func(a, b Object) (Object, error)
Or func(a, b Object) (Object, error)
Xor func(a, b Object) (Object, error)
Lshift func(a, b Object) (Object, error)
Rshift func(a, b Object) (Object, error)
Power func(a, b, mod Object) (Object, error)
Divmod func(a, b Object) (Object, error)
Negative func(o Object) (Object, error)
Positive func(o Object) (Object, error)
Absolute func(o Object) (Object, error)
Invert func(o Object) (Object, error)
Bool func(o Object) (bool, error)
Int func(o Object) (Object, error)
Float func(o Object) (Object, error)
// Index is nb_index: returns an int produced by __index__. nil
// signals the type is not "index-able" (PyIndex_Check returns 0).
//
// CPython: Include/cpython/object.h nb_index
Index func(o Object) (Object, error)
// In-place slots. Each is the i= counterpart of the binary op
// above; when nil the abstract layer falls back to the regular
// (non-in-place) op, matching binary_iop1.
//
// CPython: Include/cpython/object.h nb_inplace_*
InPlaceAdd func(a, b Object) (Object, error)
InPlaceSubtract func(a, b Object) (Object, error)
InPlaceMultiply func(a, b Object) (Object, error)
InPlaceMatrixMultiply func(a, b Object) (Object, error)
InPlaceTrueDivide func(a, b Object) (Object, error)
InPlaceFloorDivide func(a, b Object) (Object, error)
InPlaceRemainder func(a, b Object) (Object, error)
InPlaceAnd func(a, b Object) (Object, error)
InPlaceOr func(a, b Object) (Object, error)
InPlaceXor func(a, b Object) (Object, error)
InPlaceLshift func(a, b Object) (Object, error)
InPlaceRshift func(a, b Object) (Object, error)
InPlacePower func(a, b, mod Object) (Object, error)
}
NumberMethods is the v0.2 subset of tp_as_number. The reflected variants are handled by the abstract layer; concrete types only implement the forward direction.
CPython: Include/cpython/object.h:L195 PyNumberMethods
type Object ¶
type Object interface {
// Type returns the object's type. Mirrors Py_TYPE.
Type() *Type
// Hdr returns a pointer to the embedded Header so generic
// runtime code can reach the refcount without knowing the
// concrete shape. CPython reaches the same field by casting to
// PyObject*.
Hdr() *Header
}
Object is the interface every Python value satisfies. Concrete types embed *Header (or *VarHeader) and add their own fields.
CPython: Include/object.h:L107 PyObject (interface analog)
func Call ¶ added in v0.6.0
Call is PyObject_Call: the legacy entry that hands a positional tuple and keyword dict to whatever path the callable advertises. vectorcall-capable types take a fast path; everything else lands in tp_call via MakeTpCall.
CPython: Objects/call.c:370 PyObject_Call (forwards to _PyObject_Call)
func CallNoArgs ¶ added in v0.6.0
CallNoArgs is PyObject_CallNoArgs; a zero-arg vectorcall.
CPython: Objects/call.c:101 PyObject_CallNoArgs
func CallObject ¶ added in v0.6.0
CallObject is PyObject_CallObject. args may be nil, in which case it behaves like CallNoArgs; otherwise it is treated as a positional tuple.
CPython: Objects/call.c:460 PyObject_CallObject
func CallOneArg ¶ added in v0.6.0
CallOneArg is PyObject_CallOneArg; a single-positional vectorcall that reserves the args[-1] slot via VectorcallArgumentsOffset.
CPython: Objects/call.c:386 PyObject_CallOneArg
func CallPrepend ¶ added in v0.10.1
CallPrepend mirrors _PyObject_Call_Prepend: builds a fresh args stack with obj at slot 0 followed by the positional tuple, then dispatches via VectorcallDict so the keyword dict is honored without first materializing it as kwnames.
CPython: Objects/call.c:478 _PyObject_Call_Prepend
func Ellipsis ¶ added in v0.10.1
func Ellipsis() Object
Ellipsis returns the singleton Ellipsis value. Mirrors Py_Ellipsis.
CPython: Include/object.h Py_Ellipsis
func False ¶
func False() Object
False returns the False singleton. Mirrors Py_False.
CPython: Include/object.h:L857 Py_False
func GenericGetAttr ¶ added in v0.10.1
GenericGetAttr is the default Getattro slot. It looks up name in the type's MRO and:
- calls DescrGet if the descriptor is a data descriptor (has both DescrGet and DescrSet);
- calls DescrGet if it is a non-data descriptor (has only DescrGet);
- returns the descriptor itself if it has neither slot (a plain class attribute);
- raises AttributeError when nothing is found.
Instance __dict__ lookup is not yet implemented; data descriptors always win and missing attributes always raise AttributeError, which matches CPython's behavior for types without Py_TPFLAGS_MANAGED_DICT.
CPython: Objects/object.c:1932 PyObject_GenericGetAttr
func GetAttr ¶ added in v0.6.0
GetAttr fetches o.name. Routes through the type's Getattro slot. Returns AttributeError when the type exposes no attribute access.
CPython: Objects/object.c:1290 PyObject_GetAttr
func GetItem ¶ added in v0.10.1
GetItem returns o[key]. Mappings receive the key as-is; sequences require an integer key and route through Sequence.GetItem.
CPython: Objects/abstract.c:154 PyObject_GetItem
func InternFromString ¶ added in v0.10.1
InternFromString returns the canonical *Unicode for s, allocating a new one if the table didn't have one already. Mirrors PyUnicode_InternFromString.
CPython: Objects/unicodeobject.c:16151 PyUnicode_InternFromString
func Iter ¶ added in v0.10.1
Iter returns iter(o). Mirrors PyObject_GetIter.
CPython: Objects/abstract.c:2786 PyObject_GetIter
func IterNext ¶ added in v0.10.1
IterNext advances o by one. Equivalent to next(o), and propagates ErrStopIteration when the iterator is exhausted.
CPython: Objects/abstract.c:2842 PyIter_Next
func MakeTpCall ¶ added in v0.6.0
MakeTpCall is the slow path used when a callable does not advertise vectorcall. It builds the (args_tuple, kwargs_dict) shape the tp_call slot expects and dispatches through it.
CPython: Objects/call.c:200 _PyObject_MakeTpCall
func MappingGetItemString ¶ added in v0.10.1
MappingGetItemString returns o[key] where key is a Go string. Mirrors PyMapping_GetItemString: builds a transient str and routes through PyObject_GetItem.
CPython: Objects/abstract.c:2299 PyMapping_GetItemString
func MappingGetOptionalItem ¶ added in v0.10.1
MappingGetOptionalItem returns (value, true, nil) when o[key] exists, (nil, false, nil) when the lookup raises KeyError, and (nil, false, err) for any other error. Lets callers distinguish "absent" from "broken" without burning an exception. Matches PyMapping_GetOptionalItem's int return: 1, 0, -1.
CPython: Objects/abstract.c:207 PyMapping_GetOptionalItem
func MappingGetOptionalItemString ¶ added in v0.10.1
MappingGetOptionalItemString is the string-key form of MappingGetOptionalItem.
CPython: Objects/abstract.c:2316 PyMapping_GetOptionalItemString
func NewBool ¶
NewBool returns the True or False singleton. Mirrors PyBool_FromLong.
CPython: Objects/boolobject.c:L33 PyBool_FromLong
func NewStr ¶ added in v0.3.0
NewStr wraps s in a Unicode object. The constructor walks the runes to determine the narrowest PEP 393 kind: ASCII-only strings get kind 1 + ascii=true; strings with all code points < 0x100 get kind 1 (Latin-1); < 0x10000 get kind 2; anything with an astral codepoint gets kind 4.
CPython: Objects/unicodeobject.c:L1985 PyUnicode_FromString
func None ¶
func None() Object
None returns the singleton None value. Mirrors Py_None.
CPython: Include/object.h:L820 Py_None
func NotImplemented ¶
func NotImplemented() Object
NotImplemented returns the singleton NotImplemented value. Mirrors Py_NotImplemented.
CPython: Include/object.h:L863 Py_NotImplemented
func NumberAbsolute ¶ added in v0.10.1
NumberAbsolute is abs(o).
CPython: Objects/abstract.c:1384 PyNumber_Absolute
func NumberAdd ¶ added in v0.10.1
NumberAdd is a + b. Falls through to Sequence.Concat on LHS when no number slot accepts the operands, mirroring CPython's PyNumber_Add.
CPython: Objects/abstract.c:1128 PyNumber_Add
func NumberDivmod ¶ added in v0.10.1
NumberDivmod is divmod(a, b).
CPython: Objects/abstract.c:1125 PyNumber_Divmod
func NumberFloorDivide ¶ added in v0.10.1
NumberFloorDivide is a // b.
CPython: Objects/abstract.c:1185 PyNumber_FloorDivide
func NumberInPlaceAdd ¶ added in v0.10.1
NumberInPlaceAdd is a += b. Falls through to sq_concat / sq_inplace_concat on LHS when the number protocol doesn't apply.
CPython: Objects/abstract.c:1297 PyNumber_InPlaceAdd
func NumberInPlaceAnd ¶ added in v0.10.1
NumberInPlaceAnd is a &= b.
CPython: Objects/abstract.c:1287 PyNumber_InPlaceAnd
func NumberInPlaceFloorDivide ¶ added in v0.10.1
NumberInPlaceFloorDivide is a //= b.
CPython: Objects/abstract.c:1292 PyNumber_InPlaceFloorDivide
func NumberInPlaceLshift ¶ added in v0.10.1
NumberInPlaceLshift is a <<= b.
CPython: Objects/abstract.c:1288 PyNumber_InPlaceLshift
func NumberInPlaceMatrixMultiply ¶ added in v0.10.1
NumberInPlaceMatrixMultiply is a @= b.
CPython: Objects/abstract.c:1291 PyNumber_InPlaceMatrixMultiply
func NumberInPlaceMultiply ¶ added in v0.10.1
NumberInPlaceMultiply is a *= b. Falls through to sq_repeat / sq_inplace_repeat as PyNumber_InPlaceMultiply does.
CPython: Objects/abstract.c:1320 PyNumber_InPlaceMultiply
func NumberInPlaceOr ¶ added in v0.10.1
NumberInPlaceOr is a |= b.
CPython: Objects/abstract.c:1285 PyNumber_InPlaceOr
func NumberInPlacePower ¶ added in v0.10.1
NumberInPlacePower is a **= b.
CPython: Objects/abstract.c:1349 PyNumber_InPlacePower
func NumberInPlaceRemainder ¶ added in v0.10.1
NumberInPlaceRemainder is a %= b.
CPython: Objects/abstract.c:1294 PyNumber_InPlaceRemainder
func NumberInPlaceRshift ¶ added in v0.10.1
NumberInPlaceRshift is a >>= b.
CPython: Objects/abstract.c:1289 PyNumber_InPlaceRshift
func NumberInPlaceSubtract ¶ added in v0.10.1
NumberInPlaceSubtract is a -= b.
CPython: Objects/abstract.c:1290 PyNumber_InPlaceSubtract
func NumberInPlaceTrueDivide ¶ added in v0.10.1
NumberInPlaceTrueDivide is a /= b.
CPython: Objects/abstract.c:1293 PyNumber_InPlaceTrueDivide
func NumberInPlaceXor ¶ added in v0.10.1
NumberInPlaceXor is a ^= b.
CPython: Objects/abstract.c:1286 PyNumber_InPlaceXor
func NumberIndex ¶ added in v0.10.1
NumberIndex returns o coerced to int via __index__. Returns the receiver unchanged when it is already an int. Bool routes through IntFromBool to drop the bool subtype.
CPython: Objects/abstract.c:1446 PyNumber_Index
func NumberInvert ¶ added in v0.10.1
NumberInvert is ~o.
CPython: Objects/abstract.c:1383 PyNumber_Invert
func NumberLshift ¶ added in v0.10.1
NumberLshift is a << b.
CPython: Objects/abstract.c:1122 PyNumber_Lshift
func NumberMatrixMultiply ¶ added in v0.10.1
NumberMatrixMultiply is a @ b.
CPython: Objects/abstract.c:1184 PyNumber_MatrixMultiply
func NumberMultiply ¶ added in v0.10.1
NumberMultiply is a * b. Falls through to Sequence.Repeat on either side when no number slot accepts the operands, mirroring PyNumber_Multiply.
CPython: Objects/abstract.c:1166 PyNumber_Multiply
func NumberNegative ¶ added in v0.10.1
NumberNegative is -o.
CPython: Objects/abstract.c:1381 PyNumber_Negative
func NumberPositive ¶ added in v0.10.1
NumberPositive is +o.
CPython: Objects/abstract.c:1382 PyNumber_Positive
func NumberPower ¶ added in v0.10.1
NumberPower is pow(a, b, mod). mod may be nil.
CPython: Objects/abstract.c:1190 PyNumber_Power
func NumberRemainder ¶ added in v0.10.1
NumberRemainder is a % b.
CPython: Objects/abstract.c:1187 PyNumber_Remainder
func NumberRshift ¶ added in v0.10.1
NumberRshift is a >> b.
CPython: Objects/abstract.c:1123 PyNumber_Rshift
func NumberSubtract ¶ added in v0.10.1
NumberSubtract is a - b.
CPython: Objects/abstract.c:1124 PyNumber_Subtract
func NumberTrueDivide ¶ added in v0.10.1
NumberTrueDivide is a / b.
CPython: Objects/abstract.c:1186 PyNumber_TrueDivide
func RichCmp ¶
RichCmp dispatches to tp_richcompare. Returns NotImplemented when neither operand handles the comparison. Mirrors PyObject_RichCompare.
CPython: Objects/object.c:L737 PyObject_RichCompare
func SequenceConcat ¶ added in v0.10.1
SequenceConcat is s + o restricted to the sequence protocol. Falls back to nb_add when both operands look like sequences but the LHS has no sq_concat, mirroring the user-class shim in CPython.
CPython: Objects/abstract.c:1712 PySequence_Concat
func SequenceFast ¶ added in v0.10.1
SequenceFast returns v as-is when it is already a list or tuple, otherwise materializes it into a fresh list. m is the TypeError message used when v is not iterable.
CPython: Objects/abstract.c:2095 PySequence_Fast
func SequenceGetItem ¶ added in v0.10.1
SequenceGetItem is s[i] on the sequence protocol. Negative indices are normalized via sq_length the way PySequence_GetItem does; callers that already have a non-negative index can skip that work and call the slot directly.
CPython: Objects/abstract.c:1832 PySequence_GetItem
func SequenceInPlaceConcat ¶ added in v0.10.1
SequenceInPlaceConcat is s += o on the sequence protocol. Tries sq_inplace_concat, then sq_concat, then nb_inplace_add / nb_add, matching PySequence_InPlaceConcat.
CPython: Objects/abstract.c:1769 PySequence_InPlaceConcat
func SequenceInPlaceRepeat ¶ added in v0.10.1
SequenceInPlaceRepeat is s *= count on the sequence protocol. Tries sq_inplace_repeat, then sq_repeat, then nb_inplace_multiply / nb_multiply, matching PySequence_InPlaceRepeat.
CPython: Objects/abstract.c:1798 PySequence_InPlaceRepeat
func SequenceRepeat ¶ added in v0.10.1
SequenceRepeat is s * count. Falls back to nb_multiply against a fresh int when sq_repeat is missing, the way CPython's PySequence_Repeat does for user classes that defined __mul__.
CPython: Objects/abstract.c:1738 PySequence_Repeat
func True ¶
func True() Object
True returns the True singleton. Mirrors Py_True.
CPython: Include/object.h:L860 Py_True
func TypeOf ¶ added in v0.10.1
TypeOf returns o's type as an Object. Mirrors PyObject_Type; the result is the type singleton, not a fresh value.
CPython: Objects/abstract.c:42 PyObject_Type
func Vectorcall ¶ added in v0.6.0
Vectorcall is the PEP 590 entry point used by the eval loop's CALL family. nargsf is the positional count plus the optional VectorcallArgumentsOffset flag; kwnames carries keyword names whose values live at args[nargs..nargs+nkwnames].
CPython: Objects/call.c:323 PyObject_Vectorcall (forwards to _PyObject_VectorcallTstate, Include/internal/pycore_call.h:162)
func VectorcallDict ¶ added in v0.10.1
VectorcallDict is the PyObject_VectorcallDict entry: same shape as Vectorcall but the keyword side is a *Dict instead of (kwnames, trailing args). Empty/nil kwargs short-circuit to a plain vectorcall; otherwise the dict is unpacked into kwnames + values appended to a fresh stack so the underlying slot sees the standard vectorcall layout.
CPython: Objects/call.c:154 PyObject_VectorcallDict (forwards to Objects/call.c:110 _PyObject_VectorcallDictTstate)
func VectorcallPrepend ¶ added in v0.10.1
func VectorcallPrepend(callable Object, arg Object, args []Object, nargsf uint, kwnames *Tuple) (Object, error)
VectorcallPrepend prepends arg to the positional portion of args and dispatches the result. CPython exploits the VectorcallArgumentsOffset hint to overwrite args[-1] in place; Go slices can't address the slot before a sub-slice's start, so gopy always allocates a fresh stack regardless of the OFFSET bit. The behavioral contract matches; only the alloc-saving fast path is missing.
CPython: Objects/call.c:829 _PyObject_VectorcallPrepend
type OrderedDict ¶ added in v0.10.1
type OrderedDict struct {
Header
// contains filtered or unexported fields
}
OrderedDict is the OrderedDict singleton. Mirrors PyODictObject.
CPython: Objects/odictobject.c:489 _odictobject
func NewOrderedDict ¶ added in v0.10.1
func NewOrderedDict() *OrderedDict
NewOrderedDict builds an empty OrderedDict.
CPython: Objects/odictobject.c:1693 PyODict_New
func (*OrderedDict) Contains ¶ added in v0.10.1
func (od *OrderedDict) Contains(key Object) (bool, error)
Contains reports whether key is in the dict.
func (*OrderedDict) DelItem ¶ added in v0.10.1
func (od *OrderedDict) DelItem(key Object) error
DelItem removes key, unlinking the node from the order list.
CPython: Objects/odictobject.c:1662 PyODict_DelItem_LockHeld
func (*OrderedDict) GetItem ¶ added in v0.10.1
func (od *OrderedDict) GetItem(key Object) (Object, error)
GetItem looks up key. Returns errKeyNotFound when absent.
func (*OrderedDict) Len ¶ added in v0.10.1
func (od *OrderedDict) Len() int
Len returns the number of items.
func (*OrderedDict) MoveToEnd ¶ added in v0.10.1
func (od *OrderedDict) MoveToEnd(key Object, last bool) error
MoveToEnd re-positions an existing key to the tail of the link list (last=true) or the head (last=false). Raises KeyError when absent.
CPython: Objects/odictobject.c:1325 OrderedDict_move_to_end_impl
func (*OrderedDict) PopItem ¶ added in v0.10.1
func (od *OrderedDict) PopItem(last bool) (Object, Object, error)
PopItem removes and returns the (key, value) at the tail (last=true) or head (last=false). Raises KeyError on an empty dict.
CPython: Objects/odictobject.c:1155 OrderedDict_popitem_impl
func (*OrderedDict) SetItem ¶ added in v0.10.1
func (od *OrderedDict) SetItem(key, value Object) error
SetItem inserts or replaces. New keys go to the tail of the link list; replacement of an existing key leaves the order alone.
CPython: Objects/odictobject.c:1622 _PyODict_SetItem_KnownHash_LockHeld
type PositionEntry ¶ added in v0.5.5
PositionEntry adds the column span; matches the PEP 657 four-field position used for fine-grained traceback rendering.
CPython: Objects/codeobject.c:1252 PyCode_Addr2Location output.
func CoAddr2Location ¶ added in v0.6.0
func CoAddr2Location(c *Code, addr int) (PositionEntry, bool)
CoAddr2Location returns the PositionEntry covering bytecode byte offset addr, or false when no entry covers it. Mirrors the single-address form of PyCode_Addr2Location, sparing callers the linear scan when they have a precomputed entries slice.
CPython: Objects/codeobject.c:1252 PyCode_Addr2Location
func CoPositions ¶ added in v0.5.5
func CoPositions(c *Code) []PositionEntry
CoPositions decodes the PEP 626 line table into one PositionEntry per coalesced run, in source order. Start/End are bytecode bytes (1 codeunit = 2 bytes); Column / EndColumn are -1 when the form omits column information; Line / EndLine are -1 for the "none" form.
CPython: Objects/codeobject.c:1199 advance_with_locations (called in a loop).
type Property ¶ added in v0.10.1
type Property struct {
Header
// contains filtered or unexported fields
}
Property is the property descriptor.
CPython: Include/cpython/descrobject.h:39 propertyobject
func NewProperty ¶ added in v0.10.1
NewProperty builds a property from up to four arguments. Any of them may be nil; nil fget makes the property write-only (read raises AttributeError), nil fset makes it read-only, and so on.
CPython: Objects/descrobject.c:1736 property_init
func (*Property) Deleter ¶ added in v0.10.1
Deleter returns a copy of p with fdel replaced. Powers the @prop.deleter decorator.
CPython: Objects/descrobject.c:1695 property_deleter
type Range ¶
Range is the Python range object. Bounds are stored as Int so the arithmetic stays correct for the full int range.
CPython: Objects/rangeobject.c:L19 rangeobject
type Reversed ¶ added in v0.10.1
type Reversed struct {
Header
// contains filtered or unexported fields
}
Reversed backs reversed(seq). It walks the sequence backward via the SequenceMethods.GetItem slot, decrementing index from len-1.
CPython: Python/bltinmodule.c:2627 reversedobject
func NewReversed ¶ added in v0.10.1
NewReversed wraps a sequence as reversed(seq). The sequence must expose Sequence.Length and Sequence.GetItem; otherwise an error is returned. CPython also routes through __reversed__ when present; that hook isn't wired in gopy yet.
CPython: Python/bltinmodule.c:2654 reversed_new_impl
type SeqIter ¶ added in v0.10.1
type SeqIter struct {
Header
// contains filtered or unexported fields
}
SeqIter is the iterator returned by iter(seq) when seq lacks tp_iter but has a sequence GetItem slot.
CPython: Objects/iterobject.c:8 seqiterobject
func NewSeqIter ¶ added in v0.10.1
NewSeqIter wraps a sequence as iter(seq). The sequence must have a SequenceMethods.GetItem slot; otherwise the iterator stops on the first call to next().
CPython: Objects/iterobject.c:32 PySeqIter_New
type SequenceMethods ¶
type SequenceMethods struct {
Length func(o Object) (int, error)
Concat func(a, b Object) (Object, error)
Repeat func(o Object, n int) (Object, error)
GetItem func(o Object, i int) (Object, error)
SetItem func(o Object, i int, v Object) error
Contains func(o, v Object) (bool, error)
InPlaceConcat func(a, b Object) (Object, error)
InPlaceRepeat func(o Object, n int) (Object, error)
}
SequenceMethods is the v0.2 subset of tp_as_sequence.
CPython: Include/cpython/object.h:L262 PySequenceMethods
type Set ¶ added in v0.8.0
type Set struct {
Header
// contains filtered or unexported fields
}
Set is the mutable Python set type.
CPython: Objects/setobject.c:L544 PySetObject
func NewFrozenset ¶ added in v0.8.0
NewFrozenset creates a frozenset from the given items.
CPython: Objects/setobject.c:L2300 PyFrozenSet_New
func NewSet ¶ added in v0.8.0
func NewSet() *Set
NewSet creates an empty mutable set.
CPython: Objects/setobject.c:L2267 PySet_New (empty case)
func (*Set) Add ¶ added in v0.8.0
Add inserts key into the set. Returns an error if key is unhashable or if the set is frozen.
CPython: Objects/setobject.c:L413 set_add_key
func (*Set) Contains ¶ added in v0.8.0
Contains reports whether key is in the set.
CPython: Objects/setobject.c:L1777 set_contains_key
func (*Set) Difference ¶ added in v0.10.1
Difference returns self \ ⋃others.
CPython: Objects/setobject.c:1750 set_difference_multi
func (*Set) Discard ¶ added in v0.8.0
Discard removes key if present. Does nothing on miss. Errors if frozen.
CPython: Objects/setobject.c:L743 set_discard_key
func (*Set) Intersection ¶ added in v0.10.1
Intersection returns self ∩ others. Empty result when any operand is empty. Order of evaluation follows CPython: walk the smallest operand and probe the others for each candidate.
CPython: Objects/setobject.c:1611 set_intersection
func (*Set) IsDisjoint ¶ added in v0.10.1
IsDisjoint reports whether self and other share no elements.
CPython: Objects/setobject.c:2185 set_isdisjoint
func (*Set) IsSubset ¶ added in v0.10.1
IsSubset reports whether every element of self is in other.
CPython: Objects/setobject.c:1986 set_issubset
func (*Set) IsSuperset ¶ added in v0.10.1
IsSuperset reports whether every element of other is in self.
CPython: Objects/setobject.c:2014 set_issuperset
func (*Set) Items ¶ added in v0.8.0
Items returns a snapshot of the current members.
CPython: Objects/setobject.c:L1815 PySet_GET_SIZE + iteration
func (*Set) Len ¶ added in v0.8.0
Len returns the number of items.
CPython: Objects/setobject.c:L2201 PySet_Size
func (*Set) SymmetricDifference ¶ added in v0.10.1
SymmetricDifference returns self △ other: items in exactly one of the two operands.
CPython: Objects/setobject.c:1881 set_symmetric_difference
type SharedKeys ¶ added in v0.10.1
type SharedKeys struct {
// contains filtered or unexported fields
}
SharedKeys is the shared keys table that every instance of a class points at. Holds the unicode key names and their cached hashes; the per-instance values[] lives back in the Dict. Building a SharedKeys always succeeds (the names are validated as str by the caller), but any subsequent insert of a key not in this set converts the dict out of split mode.
CPython: Objects/dictobject.c:567 PyDictKeysObject (DICT_KEYS_SPLIT)
func NewSharedKeys ¶ added in v0.10.1
func NewSharedKeys(names []string) (*SharedKeys, error)
NewSharedKeys builds a SharedKeys from a list of attribute names. Each name's hash is cached so split-mode lookups don't rehash the shared key on every probe.
CPython: Objects/dictobject.c:625 new_keys_object (with split flag)
func (*SharedKeys) HasKey ¶ added in v0.10.1
func (sk *SharedKeys) HasKey(name string) bool
HasKey reports whether name is one of the shared keys. Used by SetItem to decide whether an insert keeps the dict in split mode or has to materialize it to combined.
func (*SharedKeys) Len ¶ added in v0.10.1
func (sk *SharedKeys) Len() int
Len returns the number of shared keys.
type Slice ¶
Slice is the Python slice object: start, stop, step.
CPython: Include/cpython/sliceobject.h:L8 PySliceObject
func NewSlice ¶
NewSlice builds a slice. Any of start/stop/step may be None.
CPython: Objects/sliceobject.c:L165 PySlice_New
func (*Slice) GetIndices ¶ added in v0.10.1
GetIndices is the (start, stop, step, slicelen) bundle that callers want most of the time.
CPython: Objects/sliceobject.c:308 PySlice_GetIndicesEx
func (*Slice) Indices ¶ added in v0.10.1
Indices is the slice.indices(length) Python method: returns the triple as a Tuple. Length must be non-negative.
CPython: Objects/sliceobject.c slice_indices_impl
type StaticMethod ¶ added in v0.10.1
type StaticMethod struct {
Header
// contains filtered or unexported fields
}
StaticMethod is the descriptor that strips the descriptor protocol off a function: __get__ just returns the wrapped callable, so calling it through an instance does not prepend self.
CPython: Include/cpython/funcobject.h StaticMethod (analog)
func NewStaticMethod ¶ added in v0.10.1
func NewStaticMethod(fn Object) *StaticMethod
NewStaticMethod wraps fn so attribute access on an instance returns the callable directly without binding self.
CPython: Objects/funcobject.c:1184 sm_init
func (*StaticMethod) Func ¶ added in v0.10.1
func (sm *StaticMethod) Func() Object
Func returns the wrapped callable.
type StructSeq ¶ added in v0.10.1
type StructSeq struct {
VarHeader
// contains filtered or unexported fields
}
StructSeq is the per-instance value: a struct-sequence whose Type records the field layout and whose data is a flat slice of Objects the same length as Type.fieldNames.
CPython: Objects/structseq.c:30 PyStructSequence
func NewStructSeq ¶ added in v0.10.1
NewStructSeq builds an instance of tp with values. Values must match the field count declared at NewStructSeqType time; mismatch is a programmer error and panics.
CPython: Objects/structseq.c:113 PyStructSequence_New
func (*StructSeq) AsTuple ¶ added in v0.10.1
AsTuple snapshots the struct-sequence into a plain tuple. CPython uses this for str/repr/hash via tp_as_sequence delegation; here we expose it so consumers that want a "real" tuple can drop the attribute facade.
CPython: Objects/structseq.c:78 structseq_reduce (tuple build)
type StructSeqField ¶ added in v0.10.1
StructSeqField names one positional slot of a struct-sequence type. CPython carries an optional docstring per field; gopy stashes Doc on the Type rather than per-field, so this stays minimal.
CPython: Include/structseq.h:21 PyStructSequence_Field
type Super ¶ added in v0.10.1
type Super struct {
Header
// contains filtered or unexported fields
}
Super carries the three slots PyTypeObject's superobject exposes: the explicit class, the instance (or class) the lookup is bound to, and the cached type to walk for the MRO.
CPython: Objects/typeobject.c:11771 superobject
func NewSuper ¶ added in v0.10.1
NewSuper builds a Super tied to (typ, obj). obj==nil produces an unbound super (the form bound later via tp_descr_get). When obj is not nil supercheck must validate it; an error here surfaces the TypeError CPython raises in super_init.
CPython: Objects/typeobject.c:12148 super_init_impl
type Tuple ¶
type Tuple struct {
VarHeader
// contains filtered or unexported fields
}
Tuple is the Python tuple, an immutable ordered sequence.
CPython: Include/cpython/tupleobject.h:L8 PyTupleObject
func CoerceStarArgs ¶ added in v0.10.1
CoerceStarArgs takes the iterable feeding a `f(*args)` call and produces a real *Tuple. Tuples pass through. Other iterables get drained into a fresh tuple via Iter/IterNext, mirroring the PySequence_Tuple coercion CPython performs in CALL_FUNCTION_EX.
CPython: Python/bytecodes.c CALL_FUNCTION_EX (forces tuple via _PySequence_Tuple before dispatch).
func NewTuple ¶
NewTuple builds a tuple from items. The empty tuple returns the cached singleton.
CPython: Objects/tupleobject.c:L155 PyTuple_New
func SequenceTuple ¶ added in v0.10.1
SequenceTuple consumes v's iterator and returns a fresh tuple. PyTuple_CheckExact returns the input unchanged in CPython; gopy matches that since Tuple is immutable.
CPython: Objects/abstract.c:1996 PySequence_Tuple
func (*Tuple) Count ¶ added in v0.10.1
Count returns the number of elements equal to value. Mirrors tuple.count.
CPython: Objects/tupleobject.c:822 tuple_count
func (*Tuple) Index ¶ added in v0.10.1
Index returns the position of the first item equal to value inside [start, stop). Negative bounds are normalised the same way CPython's tuple_index does, and a missing match raises ValueError.
CPython: Objects/tupleobject.c:765 tuple_index
type Type ¶
type Type struct {
Header
Name string
// Module mirrors __module__ on a type. Empty (treated as
// "builtins") for the built-in types ported in objects/.
//
// CPython: Objects/typeobject.c:907 type_module
Module string
BaseSize int
ItemSize int
Bases []*Type
MRO []*Type
Repr func(o Object) (string, error)
Str func(o Object) (string, error)
Hash func(o Object) (int64, error)
RichCmp func(a, b Object, op CompareOp) (Object, error)
// Format is the tp_format slot. Receives the object and the
// format-spec string (the part after the colon in str.format).
// When nil, the protocol-level Format helper falls back to Str
// for empty specs and raises TypeError otherwise.
//
// CPython: Objects/typeobject.c:L8260 slot_tp_format
Format func(o Object, spec string) (string, error)
Iter func(o Object) (Object, error)
IterNext func(o Object) (Object, error)
Call func(o Object, args []Object, kwargs map[string]Object) (Object, error)
// Vectorcall is the PEP 590 fast-call slot. When non-nil, the call
// machinery uses this instead of going through Call. args is a flat
// array of positional values followed by keyword values; nargsf is
// the positional count optionally combined with the
// VectorcallArgumentsOffset flag; kwnames is a tuple of keyword
// name strings (or nil).
//
// CPython: Include/cpython/object.h tp_vectorcall_offset + Py_TPFLAGS_HAVE_VECTORCALL
Vectorcall func(callable Object, args []Object, nargsf uint, kwnames *Tuple) (Object, error)
// Getattro is the tp_getattro slot. Receives the owner and the
// attribute name (as a Str), returns the attribute value or an
// error. Mirrors getattrofunc.
//
// CPython: Include/cpython/object.h tp_getattro
Getattro func(o Object, name Object) (Object, error)
// Setattro is the tp_setattro slot. value==nil signals a delete
// (PyObject_DelAttr forwards there). Mirrors setattrofunc.
//
// CPython: Include/cpython/object.h tp_setattro
Setattro func(o Object, name Object, value Object) error
// DescrGet is the tp_descr_get slot. When a class attribute that
// implements this slot is found during instance attribute lookup,
// the lookup machinery hands it to DescrGet so the descriptor can
// produce the bound value. owner is the instance the lookup
// started from (nil when accessed on the class itself); ownerType
// is the type whose __mro__ supplied the descriptor.
//
// CPython: Include/cpython/object.h tp_descr_get
DescrGet func(descr Object, owner Object, ownerType *Type) (Object, error)
// DescrSet is the tp_descr_set slot. value==nil signals a delete.
//
// CPython: Include/cpython/object.h tp_descr_set
DescrSet func(descr Object, owner Object, value Object) error
Dealloc func(o Object)
// Finalize is the tp_finalize slot. The cycle collector invokes
// it once on each unreachable object before reclaiming, and the
// destruction path fires it from PyObject_CallFinalizer. User
// classes get this slot populated with a wrapper that calls
// __del__; built-in types fill it in directly when they need
// cleanup that runs before memory goes back.
//
// CPython: Include/cpython/object.h:237 tp_finalize
// CPython: Objects/typeobject.c slot_tp_finalize
Finalize func(o Object)
// TpTraverse mirrors tp_traverse. It calls visit on every Object
// reachable directly from o so the cycle collector can walk the
// reference graph. Returning a non-nil error short-circuits the
// traversal.
//
// CPython: Include/cpython/object.h tp_traverse
TpTraverse func(o Object, visit Visitor) error
Number *NumberMethods
Sequence *SequenceMethods
Mapping *MappingMethods
Async *AsyncMethods
// TpFlags mirrors CPython's tp_flags bitset for the subset of flags
// that affect VM dispatch (MATCH_MAPPING / MATCH_SEQUENCE).
//
// CPython: Include/object.h Py_TPFLAGS_*
TpFlags uint64
// IsUser is the gopy stand-in for Py_TPFLAGS_HEAPTYPE: true for
// classes built via NewUserType (and thus through __build_class__
// or type(name, bases, dict)). The type-call path consults this
// to decide between class construction and instance allocation.
//
// CPython: Include/object.h Py_TPFLAGS_HEAPTYPE
IsUser bool
// Slots holds the resolved __slots__ names for this user type, in
// declaration order. Empty when the class did not declare __slots__
// or the class is a built-in. Each name has a fixed index into the
// instance slots array; MemberDescr objects carry the index and act
// as data descriptors so reads/writes go through DescrGet/DescrSet.
//
// CPython: Objects/typeobject.c:4401 type_new_descriptors
Slots []string
// HasDict is true when instances of this type carry a per-instance
// __dict__. False only when the class declares __slots__ without
// __dict__ (and no base contributes one). Mirrors a non-zero
// tp_dictoffset / Py_TPFLAGS_MANAGED_DICT.
//
// CPython: Include/cpython/typeobject.h tp_dictoffset
HasDict bool
}
Type is the meta-class for every Python value. Slots not yet implemented in v0.2 are nil; the runtime checks for nil before dispatching.
CPython: Include/cpython/typeobject.h:L139 _typeobject
var AsyncGenASendType *Type
AsyncGenASendType is the type for the awaitable returned by asend() and __anext__.
CPython: Objects/genobject.c:L1879 _PyAsyncGenASend_Type
var AsyncGenAThrowType *Type
AsyncGenAThrowType is the type for the awaitable returned by athrow() and aclose().
CPython: Objects/genobject.c:L2272 _PyAsyncGenAThrow_Type
var AsyncGeneratorType *Type
AsyncGeneratorType is the type singleton for async_generator.
var CoroAwaitType *Type
CoroAwaitType is the type for the iterator that __await__ returns.
CPython: Objects/genobject.c:L1500 _PyCoroWrapper_Type
var CoroutineType *Type
CoroutineType is the type singleton for coroutine.
CPython: Objects/genobject.c:L1271 PyCoro_Type
var GeneratorType *Type
GeneratorType is the type singleton for generator.
CPython: Objects/genobject.c:L898 PyGen_Type
func FrameType ¶ added in v0.10.1
func FrameType() *Type
FrameType returns the type singleton for `frame`.
CPython: Objects/frameobject.c:1238 PyFrame_Type
func NewStructSeqType ¶ added in v0.10.1
func NewStructSeqType(name string, fields []StructSeqField) *Type
NewStructSeqType builds a struct-sequence type with the given name and ordered fields. Bases is [tuple] so isinstance(x, tuple) holds, matching CPython.
CPython: Objects/structseq.c:431 PyStructSequence_NewType
func NewType ¶
NewType constructs a built-in type with the given name and bases. Bases must be non-empty for everything except `object`. The MRO is computed via C3 linearization.
CPython: Objects/typeobject.c:L4153 type_new (adapted from)
func NewUserType ¶ added in v0.10.1
NewUserType builds a Python-defined class. bases default to [object] when empty; ns must be non-nil and is iterated for type members. __slots__ in ns triggers the slot layout machinery (CPython type_new_slots + type_new_descriptors): each slot becomes a MemberDescr at a fixed instance index, and the resulting class has no per-instance __dict__ unless a base contributes one or the slots list explicitly includes "__dict__".
CPython: Objects/typeobject.c:4153 type_new
func NoneType ¶
func NoneType() *Type
NoneType returns the type singleton for None.
CPython: Objects/object.c:L1893 _PyNone_Type
func ObjectType ¶
func ObjectType() *Type
ObjectType returns the root `object` type singleton. Mirrors PyBaseObject_Type.
CPython: Objects/typeobject.c:L6299 PyBaseObject_Type
type Unicode ¶ added in v0.10.1
type Unicode struct {
Header
// contains filtered or unexported fields
}
Unicode is the Python str type. The struct layout pins the PEP 393 fields (kind, length, ascii, ready, hash cache) plus the Go string the constructor preserves so methods that need byte-level access (encode, repr) can read it without re-walking the kind data.
CPython: Include/cpython/unicodeobject.h PyASCIIObject + PyCompactUnicodeObject
func (*Unicode) IsReady ¶ added in v0.10.1
IsReady reports whether the canonical layout is built. Always true for strings created via NewStr.
type VarHeader ¶
type VarHeader struct {
Header
// contains filtered or unexported fields
}
VarHeader extends Header with ob_size for variable-length builtins such as tuple, str, bytes, and int.
CPython: Include/object.h:L121 PyVarObject
type Visitor ¶ added in v0.10.0
Visitor is the visitproc shape passed to TpTraverse. CPython's visitproc takes a void* arg; gopy closures already capture state so the second argument is unnecessary here.
CPython: Include/cpython/object.h:L83 visitproc
type WeakProxy ¶ added in v0.10.1
type WeakProxy struct {
Header
// contains filtered or unexported fields
}
WeakProxy backs both weakref.ProxyType and weakref.CallableProxyType.
CPython: Objects/weakrefobject.c:25 PyWeakReference (proxy variants)
func NewWeakCallableProxy ¶ added in v0.10.1
NewWeakCallableProxy builds the CallableProxyType variant for referents whose type defines __call__.
CPython: Objects/weakrefobject.c:925 PyWeakref_NewProxy (callable branch picking _PyWeakref_CallableProxyType)
func NewWeakProxy ¶ added in v0.10.1
NewWeakProxy builds a non-callable weakref.proxy pointing at referent. Mirrors PyWeakref_NewProxy when the referent is not callable.
CPython: Objects/weakrefobject.c:925 PyWeakref_NewProxy
type Weakref ¶ added in v0.10.0
type Weakref struct {
Header
// contains filtered or unexported fields
}
Weakref is the weakref.ref Python object.
CPython: Objects/weakrefobject.c:25 PyWeakReference
func NewWeakref ¶ added in v0.10.0
NewWeakref builds a fresh weakref pointing at referent. callback may be None or any callable; gopy fires it when the referent is cleared by the collector.
CPython: Objects/weakrefobject.c:271 PyWeakref_NewRef
func (*Weakref) Callback ¶ added in v0.10.0
Callback returns the registered callback, or None if none was set.
Source Files
¶
- abstract_mapping.go
- abstract_number.go
- abstract_sequence.go
- async_gen.go
- bool.go
- bytearray.go
- bytes.go
- bytes_methods_wrap.go
- call.go
- call_args.go
- capsule.go
- cell.go
- cfunction.go
- code.go
- code_tables.go
- complex.go
- coroutine.go
- descr.go
- dict.go
- dict_iter.go
- dict_lookup.go
- dict_mutate.go
- dict_split.go
- ellipsis.go
- enum.go
- errors.go
- file.go
- filter.go
- float.go
- float_parse.go
- frame.go
- frame_locals.go
- function.go
- function_builtin.go
- generator.go
- generic_attr.go
- hash.go
- header.go
- identity.go
- instance.go
- int.go
- list.go
- list_misc.go
- list_resize.go
- list_sort.go
- long_arith.go
- long_bitwise.go
- long_cache.go
- long_misc.go
- long_parse.go
- map.go
- member.go
- memoryview.go
- method.go
- module.go
- mro.go
- namespace.go
- none.go
- notimpl.go
- object.go
- odict.go
- property.go
- protocol.go
- protocol_object.go
- range.go
- range_iter.go
- refcount.go
- seqiter.go
- set.go
- set_ops.go
- slice.go
- slice_indices.go
- slots.go
- str.go
- str_format.go
- str_intern.go
- str_methods.go
- str_modulo.go
- structseq.go
- super.go
- tuple.go
- tuple_misc.go
- type.go
- type_call.go
- type_repr.go
- unicode_ctype.go
- usertype.go
- weakref.go
- weakref_proxy.go