objects

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
var BoolType = NewType("bool", []*Type{IntType})

BoolType is the type singleton for bool. Mirrors PyBool_Type.

CPython: Objects/boolobject.c:L222 PyBool_Type

View Source
var BoundMethodType = NewType("method", []*Type{objectType})

BoundMethodType is the type singleton for bound methods.

CPython: Objects/classobject.c:268 PyMethod_Type

View Source
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

View Source
var ByteArrayType = NewType("bytearray", []*Type{objectType})

ByteArrayType is the type singleton for bytearray.

CPython: Objects/bytearrayobject.c:2654 PyByteArray_Type

View Source
var BytesType = NewType("bytes", []*Type{objectType})

BytesType is the type singleton for bytes. Mirrors PyBytes_Type.

CPython: Objects/bytesobject.c:3134 PyBytes_Type

View Source
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

View Source
var CallIterType = NewType("callable_iterator", []*Type{objectType})

CallIterType is the type singleton for callable_iterator.

CPython: Objects/iterobject.c:171 PyCallIter_Type

View Source
var CapsuleType = NewType("PyCapsule", []*Type{objectType})

CapsuleType is the type singleton for capsules.

CPython: Objects/capsule.c:354 PyCapsule_Type

View Source
var CellType = NewType("cell", []*Type{objectType})

CellType is the type singleton for cell objects.

CPython: Objects/cellobject.c PyCell_Type

View Source
var ClassMethodType = NewType("classmethod", []*Type{objectType})

ClassMethodType is the type singleton for classmethod.

CPython: Objects/funcobject.c:1119 PyClassMethod_Type

View Source
var CodeType = NewType("code", []*Type{objectType})

CodeType is the type singleton for code objects.

CPython: Objects/codeobject.c:2980 PyCode_Type

View Source
var ComplexType = NewType("complex", []*Type{objectType})

ComplexType is the type singleton for complex.

CPython: Objects/complexobject.c:1075 PyComplex_Type

View Source
var DictType = NewType("dict", []*Type{objectType})

DictType is the type singleton for dict. Mirrors PyDict_Type.

CPython: Objects/dictobject.c:L4023 PyDict_Type

View Source
var EnumerateType = NewType("enumerate", []*Type{objectType})

EnumerateType is the type singleton for enumerate.

CPython: Python/bltinmodule.c:1455 PyEnum_Type

View Source
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

View Source
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

View Source
var ErrStopIteration = errors.New("StopIteration")

ErrStopIteration signals end of iteration. Mirrors PyExc_StopIteration.

CPython: Objects/exceptions.c:L1937 PyExc_StopIteration

View Source
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

View Source
var FilterType = NewType("filter", []*Type{objectType})

FilterType is the type singleton for filter.

CPython: Python/bltinmodule.c:640 PyFilter_Type

View Source
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

View Source
var FrozensetType = NewType("frozenset", []*Type{objectType})

FrozensetType is the type singleton for frozenset.

CPython: Objects/setobject.c:L2468 PyFrozenSet_Type

View Source
var FunctionType = NewType("function", []*Type{objectType})

FunctionType is the type singleton for Python-defined functions.

CPython: Objects/funcobject.c:1232 PyFunction_Type

View Source
var GetSetDescrType = NewType("getset_descriptor", []*Type{objectType})

GetSetDescrType is the type singleton for getset descriptors.

CPython: Objects/descrobject.c:1620 PyGetSetDescr_Type

View Source
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

View Source
var ListType = NewType("list", []*Type{objectType})

ListType is the type singleton for list. Mirrors PyList_Type.

CPython: Objects/listobject.c:L3380 PyList_Type

View Source
var MapType = NewType("map", []*Type{objectType})

MapType is the type singleton for map.

CPython: Python/bltinmodule.c:1624 PyMap_Type

View Source
var MemberDescrType = NewType("member_descriptor", []*Type{objectType})

MemberDescrType is the type singleton for __slots__ descriptors.

CPython: Objects/descrobject.c:1623 PyMemberDescr_Type

View Source
var MemoryViewType = NewType("memoryview", []*Type{objectType})

MemoryViewType is the type singleton for memoryview.

CPython: Objects/memoryobject.c:3402 PyMemoryView_Type

View Source
var ModuleType = NewType("module", []*Type{objectType})

ModuleType is the type singleton for module objects.

CPython: Objects/moduleobject.c:766 PyModule_Type

View Source
var NamespaceType = NewType("types.SimpleNamespace", []*Type{objectType})

NamespaceType is the type singleton for SimpleNamespace.

CPython: Objects/namespaceobject.c:275 _PyNamespace_Type

View Source
var OrderedDictType = NewType("OrderedDict", []*Type{DictType})

OrderedDictType is the type singleton for collections.OrderedDict.

CPython: Objects/odictobject.c:1840 PyODict_Type

View Source
var PropertyType = NewType("property", []*Type{objectType})

PropertyType is the type singleton for property.

CPython: Objects/descrobject.c:1817 PyProperty_Type

View Source
var RangeType = NewType("range", []*Type{objectType})

RangeType is the type singleton for range. Mirrors PyRange_Type.

CPython: Objects/rangeobject.c:L949 PyRange_Type

View Source
var ReversedType = NewType("reversed", []*Type{objectType})

ReversedType is the type singleton for reversed.

CPython: Python/bltinmodule.c:2724 PyReversed_Type

View Source
var SeqIterType = NewType("iterator", []*Type{objectType})

SeqIterType is the type singleton for seqiterator.

CPython: Objects/iterobject.c:21 PySeqIter_Type

View Source
var SetType = NewType("set", []*Type{objectType})

SetType is the type singleton for set.

CPython: Objects/setobject.c:L2318 PySet_Type

View Source
var SliceType = NewType("slice", []*Type{objectType})

SliceType is the type singleton for slice. Mirrors PySlice_Type.

CPython: Objects/sliceobject.c:L325 PySlice_Type

View Source
var StaticMethodType = NewType("staticmethod", []*Type{objectType})

StaticMethodType is the type singleton for staticmethod.

CPython: Objects/funcobject.c:1233 PyStaticMethod_Type

View Source
var SuperType = NewType("super", []*Type{objectType})

SuperType is the type singleton for the cooperative super helper.

CPython: Objects/typeobject.c:12313 PySuper_Type

View Source
var TupleType = NewType("tuple", []*Type{objectType})

TupleType is the type singleton for tuple. Mirrors PyTuple_Type.

CPython: Objects/tupleobject.c:L961 PyTuple_Type

View Source
var WeakCallableProxyType = NewType("weakcallableproxy", []*Type{objectType})

WeakCallableProxyType is the type singleton for weakref.CallableProxyType.

CPython: Objects/weakrefobject.c:887 _PyWeakref_CallableProxyType

View Source
var WeakProxyType = NewType("weakproxy", []*Type{objectType})

WeakProxyType is the type singleton for weakref.ProxyType.

CPython: Objects/weakrefobject.c:852 _PyWeakref_ProxyType

View Source
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

func AdjustIndices(length int, start, stop *int, step int) int

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

func Contains(o, v Object) (bool, error)

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

func DelAttr(o Object, name Object) error

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

func DelItem(o, key Object) error

DelItem deletes o[key]. Forwards to SetItem with value==nil.

CPython: Objects/abstract.c:227 PyObject_DelItem

func Format added in v0.10.1

func Format(o Object, spec string) (string, error)

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

func GenericSetAttr(o Object, name Object, value Object) error

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

func Hash(o Object) (int64, error)

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

func HashBytes(src []byte) int64

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

func HashString(s string) int64

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

func IndexCheck(o Object) bool

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

func Is(a, b Object) bool

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

func IsAlphaRune(r rune) bool

IsAlphaRune reports whether r is a letter.

CPython: Objects/unicodectype.c:201 _PyUnicode_IsAlpha

func IsBool added in v0.10.1

func IsBool(o Object) bool

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

func IsCasedRune(r rune) bool

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

func IsDecimalRune(r rune) bool

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

func IsDigitRune(r rune) bool

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

func IsEllipsis(o Object) bool

IsEllipsis reports whether o is the Ellipsis singleton.

CPython: Objects/object.c Py_IsEllipsis (3.14+)

func IsFalse added in v0.10.1

func IsFalse(o Object) bool

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

func IsLowerRune(r rune) bool

IsLowerRune reports whether r has the Lowercase property.

CPython: Objects/unicodectype.c:160 _PyUnicode_IsLowercase

func IsNone

func IsNone(o Object) bool

IsNone reports whether o is the None singleton. Mirrors Py_IsNone.

CPython: Include/object.h:L827 Py_IsNone

func IsNotImplemented

func IsNotImplemented(o Object) bool

IsNotImplemented reports whether o is the NotImplemented singleton.

CPython: Objects/object.c:L1965 Py_IsNotImplemented

func IsNumericRune added in v0.10.1

func IsNumericRune(r rune) bool

IsNumericRune reports whether r is in any Number category.

CPython: Objects/unicodectype.c:239 _PyUnicode_IsNumeric

func IsPrintableRune added in v0.10.1

func IsPrintableRune(r rune) bool

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

func IsSpaceRune(r rune) bool

IsSpaceRune reports whether r is whitespace.

CPython: Objects/unicodectype.c:252 _PyUnicode_IsWhitespace

func IsSubtype

func IsSubtype(sub, super *Type) bool

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

func IsTitleRune(r rune) bool

IsTitleRune reports whether r has the Titlecase property.

CPython: Objects/unicodectype.c:190 _PyUnicode_IsTitlecase

func IsTrue added in v0.10.1

func IsTrue(o Object) bool

IsTrue reports whether o is the True singleton (Python `o is True`).

CPython: Include/object.h:262 Py_IsTrue

func IsTruthy

func IsTruthy(o Object) (bool, error)

IsTruthy mirrors PyObject_IsTrue.

CPython: Objects/object.c:L1671 PyObject_IsTrue

func IsUpperRune added in v0.10.1

func IsUpperRune(r rune) bool

IsUpperRune reports whether r has the Uppercase property.

CPython: Objects/unicodectype.c:175 _PyUnicode_IsUppercase

func IsXIDContinueRune added in v0.10.1

func IsXIDContinueRune(r rune) bool

IsXIDContinueRune reports whether r can continue an identifier.

CPython: Objects/unicodectype.c:294 _PyUnicode_IsXidContinue

func IsXIDStartRune added in v0.10.1

func IsXIDStartRune(r rune) bool

IsXIDStartRune reports whether r can begin an identifier.

CPython: Objects/unicodectype.c:283 _PyUnicode_IsXidStart

func Length added in v0.10.1

func Length(o Object) (int, error)

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

func LookupDescriptor(t *Type, name string) (Object, *Type)

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

func MakeStrTrans(from, to, drop string) (map[rune]rune, error)

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

func MappingCheck(o Object) bool

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

func MappingDelItem(o, key Object) error

MappingDelItem removes o[key].

CPython: Objects/abstract.c PyMapping_DelItem (forwards to PyObject_DelItem)

func MappingDelItemString added in v0.10.1

func MappingDelItemString(o Object, key string) error

MappingDelItemString removes o[key].

CPython: Objects/abstract.c PyMapping_DelItemString (forwards to PyObject_DelItem)

func MappingHasKey added in v0.10.1

func MappingHasKey(o, key Object) bool

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

func MappingHasKeyString(o Object, key string) bool

MappingHasKeyString is the string-key form.

CPython: Objects/abstract.c:2371 PyMapping_HasKeyString

func MappingHasKeyStringWithError added in v0.10.1

func MappingHasKeyStringWithError(o Object, key string) (bool, error)

MappingHasKeyStringWithError is the string-key form.

CPython: Objects/abstract.c:2353 PyMapping_HasKeyStringWithError

func MappingHasKeyWithError added in v0.10.1

func MappingHasKeyWithError(o, key Object) (bool, error)

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

func MappingLength(o Object) (int, error)

MappingLength is the historical alias for MappingSize.

CPython: Objects/abstract.c:2292 PyMapping_Length

func MappingSetItemString added in v0.10.1

func MappingSetItemString(o Object, key string, value Object) error

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

func MappingSize(o Object) (int, error)

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

func MissingArgumentsError(qualname, kind string, names []string) error

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

func MultipleValuesForArgumentError(qualname, name string) error

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

func PositionalOnlyAsKeywordError(qualname string, names []string) error

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

func Repr(o Object) (string, error)

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

func RichCmpBool(a, b Object, op CompareOp) (bool, error)

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

func SequenceCheck(s Object) bool

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

func SequenceContains(s, o Object) (bool, error)

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

func SequenceCount(s, o Object) (int, error)

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

func SequenceDelItem(s Object, i int) error

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

func SequenceIndex(s, o Object) (int, error)

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

func SequenceSetItem(s Object, i int, v Object) error

SequenceSetItem is s[i] = v on the sequence protocol.

CPython: Objects/abstract.c:1884 PySequence_SetItem

func SequenceSize added in v0.10.1

func SequenceSize(s Object) (int, error)

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

func SetAttr(o Object, name Object, value Object) error

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

func SetItem(o, key, value Object) error

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

func SetTypeDescr(t *Type, name string, d Object)

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

func Str(o Object) (string, error)

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

func StrCapitalize(s string) string

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

func StrCaseFold(s string) string

StrCaseFold approximates str.casefold via lowercasing.

CPython: Objects/unicodeobject.c:L11122 unicode_casefold_impl

func StrCenter added in v0.10.1

func StrCenter(s string, width int, fillchar rune) string

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

func StrCount(s, needle string, start, end int) int

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

func StrEndsWith(s, suffix string, start, end int) bool

StrEndsWith ports str.endswith.

CPython: Objects/unicodeobject.c:L13665 unicode_endswith_impl

func StrExpandTabs added in v0.10.1

func StrExpandTabs(s string, tabsize int) string

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

func StrFind(s, needle string, start, end int) int

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

func StrIndex(s, needle string, start, end int) (int, error)

StrIndex is StrFind that raises ValueError on miss.

CPython: Objects/unicodeobject.c:L12019 unicode_index_impl

func StrIsASCII added in v0.10.1

func StrIsASCII(s string) bool

func StrIsAlnum added in v0.10.1

func StrIsAlnum(s string) bool

func StrIsAlpha added in v0.10.1

func StrIsAlpha(s string) bool

func StrIsDecimal added in v0.10.1

func StrIsDecimal(s string) bool

func StrIsDigit added in v0.10.1

func StrIsDigit(s string) bool

func StrIsIdentifier added in v0.10.1

func StrIsIdentifier(s string) bool

func StrIsLower added in v0.10.1

func StrIsLower(s string) bool

func StrIsNumeric added in v0.10.1

func StrIsNumeric(s string) bool

func StrIsPrintable added in v0.10.1

func StrIsPrintable(s string) bool

func StrIsSpace added in v0.10.1

func StrIsSpace(s string) bool

func StrIsTitle added in v0.10.1

func StrIsTitle(s string) bool

func StrIsUpper added in v0.10.1

func StrIsUpper(s string) bool

func StrJoin added in v0.10.1

func StrJoin(sep string, parts []Object) (string, error)

StrJoin ports str.join. Each iterable item must be a *Unicode.

CPython: Objects/unicodeobject.c:L12524 unicode_join

func StrLJust added in v0.10.1

func StrLJust(s string, width int, fillchar rune) string

func StrLStrip added in v0.10.1

func StrLStrip(s, chars string) string

StrLStrip ports str.lstrip.

CPython: Objects/unicodeobject.c:L12717 unicode_lstrip_impl

func StrLower added in v0.10.1

func StrLower(s string) string

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

func StrPartition(s, sep string) (string, string, string, error)

StrPartition ports str.partition.

CPython: Objects/unicodeobject.c:L13272 unicode_partition

func StrRFind added in v0.10.1

func StrRFind(s, needle string, start, end int) int

StrRFind ports str.rfind: rightmost index of needle.

CPython: Objects/unicodeobject.c:L13048 unicode_rfind_impl

func StrRIndex added in v0.10.1

func StrRIndex(s, needle string, start, end int) (int, error)

StrRIndex is StrRFind that raises ValueError on miss.

CPython: Objects/unicodeobject.c:L13069 unicode_rindex_impl

func StrRJust added in v0.10.1

func StrRJust(s string, width int, fillchar rune) string

func StrRPartition added in v0.10.1

func StrRPartition(s, sep string) (string, string, string, error)

StrRPartition ports str.rpartition.

CPython: Objects/unicodeobject.c:L13287 unicode_rpartition

func StrRSplit added in v0.10.1

func StrRSplit(s, sep string, maxsplit int) ([]string, error)

StrRSplit ports str.rsplit.

CPython: Objects/unicodeobject.c:L13190 unicode_rsplit_impl

func StrRStrip added in v0.10.1

func StrRStrip(s, chars string) string

StrRStrip ports str.rstrip.

CPython: Objects/unicodeobject.c:L12737 unicode_rstrip_impl

func StrReplace added in v0.10.1

func StrReplace(s, old, newS string, count int) string

StrReplace ports str.replace. count<0 means all.

CPython: Objects/unicodeobject.c:L12885 unicode_replace_impl

func StrSplit added in v0.10.1

func StrSplit(s, sep string, maxsplit int) ([]string, error)

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

func StrSplitLines(s string, keepends bool) []string

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

func StrStartsWith(s, prefix string, start, end int) bool

StrStartsWith ports str.startswith.

CPython: Objects/unicodeobject.c:L13609 unicode_startswith_impl

func StrStrip added in v0.10.1

func StrStrip(s, chars string) string

StrStrip ports str.strip. chars="" means default whitespace.

CPython: Objects/unicodeobject.c:L12757 unicode_strip_impl

func StrSwapCase added in v0.10.1

func StrSwapCase(s string) string

StrSwapCase swaps each character's case.

CPython: Objects/unicodeobject.c:L11130 unicode_swapcase_impl

func StrTitle added in v0.10.1

func StrTitle(s string) string

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

func StrTranslate(s string, table map[rune]rune) string

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 StrUpper added in v0.10.1

func StrUpper(s string) string

func StrZFill added in v0.10.1

func StrZFill(s string, width int) string

StrZFill pads with leading zeros, preserving an optional +/- sign.

CPython: Objects/unicodeobject.c:L13110 unicode_zfill_impl

func ToLowerRune added in v0.10.1

func ToLowerRune(r rune) rune

ToLowerRune folds r to lowercase.

CPython: Objects/unicodectype.c:65 _PyUnicode_ToLowercase

func ToTitleRune added in v0.10.1

func ToTitleRune(r rune) rune

ToTitleRune folds r to titlecase.

CPython: Objects/unicodectype.c:117 _PyUnicode_ToTitlecase

func ToUpperRune added in v0.10.1

func ToUpperRune(r rune) rune

ToUpperRune folds r to uppercase.

CPython: Objects/unicodectype.c:91 _PyUnicode_ToUppercase

func TooManyPositionalError added in v0.10.1

func TooManyPositionalError(qualname string, given, atLeast, atMost, kwonlyGiven int) error

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

func UnexpectedKeywordError(qualname, name string) error

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

func UnpackKwargs(kwargs *Dict) (*Tuple, []Object, error)

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

func VectorcallNargs(nargsf uint) int

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

func (*AsyncGenerator) Throw added in v0.10.1

func (g *AsyncGenerator) Throw(err error) (Object, error)

Throw raises err inside the async generator. Used by athrow().

CPython: Objects/genobject.c:L2272 async_gen_athrow

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

func NewByteArray(buf []byte) *ByteArray

NewByteArray wraps a copy of buf in a ByteArray.

CPython: Objects/bytearrayobject.c:138 PyByteArray_FromStringAndSize

func (*ByteArray) Append added in v0.10.1

func (b *ByteArray) Append(v int) error

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

func (b *ByteArray) Bytes() []byte

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

func (b *ByteArray) Extend(src []byte)

Extend concatenates the bytes from src.

CPython: Objects/bytearrayobject.c:2299 bytearray_extend

func (*ByteArray) Insert added in v0.10.1

func (b *ByteArray) Insert(where int, v int) error

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

func (b *ByteArray) Len() int

Len returns the number of bytes.

CPython: Objects/bytearrayobject.c:62 PyByteArray_Size

func (*ByteArray) Pop added in v0.10.1

func (b *ByteArray) Pop(i int) (int, error)

Pop removes and returns the byte at index i. Default index in CPython is -1; the gopy port leaves that decision to the caller.

CPython: Objects/bytearrayobject.c:2267 bytearray_pop

func (*ByteArray) Reverse added in v0.10.1

func (b *ByteArray) Reverse()

Reverse reverses bytes in place.

CPython: Objects/bytearrayobject.c:2226 bytearray_reverse

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

func BytesFromHex(s string) (*Bytes, error)

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

func MakeBytesTrans(frm, to []byte) (*Bytes, error)

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

func NewBytes(buf []byte) *Bytes

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

func NewBytesFromString(s string) *Bytes

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

func (b *Bytes) Bytes() []byte

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

func (b *Bytes) Center(width int, fill byte) *Bytes

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

func (b *Bytes) Count(sub []byte, start, end int) int

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

func (b *Bytes) EndsWith(suffix []byte, start, end int) bool

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

func (b *Bytes) ExpandTabs(tabsize int) *Bytes

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

func (b *Bytes) Find(sub []byte, start, end int) int

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

func (b *Bytes) Hex(sep byte, bytesPerSep int) string

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

func (b *Bytes) Index(sub []byte, start, end int) (int, error)

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

func (b *Bytes) Join(seq []Object) (*Bytes, error)

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

func (b *Bytes) LJust(width int, fill byte) *Bytes

LJust pads on the right.

CPython: Objects/stringlib/transmogrify.h:139 stringlib_ljust

func (*Bytes) LStrip added in v0.10.1

func (b *Bytes) LStrip(chars []byte) *Bytes

LStrip strips only the leading run.

CPython: Objects/bytesobject.c:2099 bytes_lstrip_impl

func (*Bytes) Len added in v0.10.1

func (b *Bytes) Len() int

Len returns the number of bytes.

CPython: Objects/bytesobject.c:1228 PyBytes_Size

func (*Bytes) Partition added in v0.10.1

func (b *Bytes) Partition(sep []byte) (*Bytes, *Bytes, *Bytes, error)

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

func (b *Bytes) RFind(sub []byte, start, end int) int

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

func (b *Bytes) RIndex(sub []byte, start, end int) (int, error)

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

func (b *Bytes) RJust(width int, fill byte) *Bytes

RJust pads on the left.

CPython: Objects/stringlib/transmogrify.h:155 stringlib_rjust

func (*Bytes) RPartition added in v0.10.1

func (b *Bytes) RPartition(sep []byte) (*Bytes, *Bytes, *Bytes, error)

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

func (b *Bytes) RSplit(sep []byte, maxsplit int) ([]*Bytes, error)

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

func (b *Bytes) RStrip(chars []byte) *Bytes

RStrip strips only the trailing run.

CPython: Objects/bytesobject.c:2117 bytes_rstrip_impl

func (*Bytes) Replace added in v0.10.1

func (b *Bytes) Replace(old, repl []byte, count int) *Bytes

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

func (b *Bytes) Split(sep []byte, maxsplit int) ([]*Bytes, error)

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

func (b *Bytes) SplitLines(keepends bool) []*Bytes

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

func (b *Bytes) StartsWith(prefix []byte, start, end int) bool

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

func (b *Bytes) String() string

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

func (b *Bytes) Strip(chars []byte) *Bytes

Strip removes leading and trailing bytes that match chars. A nil chars defaults to ASCII whitespace.

CPython: Objects/bytesobject.c:2081 bytes_strip_impl

func (*Bytes) Translate added in v0.10.1

func (b *Bytes) Translate(table, deleteChars []byte) (*Bytes, error)

Translate maps each byte through table (a 256-byte lookup) and drops any byte that appears in delete. A nil table is the identity. CPython requires the table to be exactly 256 bytes when present.

CPython: Objects/bytesobject.c:2155 bytes_translate_impl

func (*Bytes) ZFill added in v0.10.1

func (b *Bytes) ZFill(width int) *Bytes

ZFill pads on the left with '0', preserving a leading '+' or '-'.

CPython: Objects/stringlib/transmogrify.h:225 stringlib_zfill

type CFunction added in v0.10.1

type CFunction struct {
	Header
	Def    *MethodDef
	Self   Object
	Module Object
	Cls    *Type
}

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

func NewCFunction(def *MethodDef, self Object, module Object, cls *Type) (*CFunction, error)

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

func NewCallIter(callable, sentinel Object) *CallIter

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

func NewCapsule(pointer any, name string, destructor func(*Capsule)) (*Capsule, error)

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

func (c *Capsule) Context() any

Context returns the user-supplied context value.

CPython: Objects/capsule.c PyCapsule_GetContext

func (*Capsule) GetPointer added in v0.10.1

func (c *Capsule) GetPointer(name string) (any, error)

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

func (c *Capsule) IsValid(name string) bool

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

func (c *Capsule) Name() string

Name returns the capsule's name.

CPython: Objects/capsule.c PyCapsule_GetName

func (*Capsule) SetContext added in v0.10.1

func (c *Capsule) SetContext(ctx any)

SetContext attaches an opaque context value to the capsule.

CPython: Objects/capsule.c PyCapsule_SetContext

type Cell added in v0.6.0

type Cell struct {
	Header
	Contents Object // may be nil to mean "unbound"
}

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

func NewCell added in v0.6.0

func NewCell(contents Object) *Cell

NewCell builds a cell holding contents. Pass nil for an unbound cell.

CPython: Objects/cellobject.c PyCell_New

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.

func (*Code) Copy added in v0.10.1

func (c *Code) Copy() *Code

Copy returns a deep copy of c. Slice fields are duplicated so the result can be mutated independently.

func (*Code) Replace added in v0.10.1

func (c *Code) Replace(r CodeReplace) (*Code, error)

Replace returns a copy of c with the fields named in r overridden. The receiver is not modified.

CPython: Objects/codeobject.c:2858 code_replace_impl

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

const (
	// CompareLT is `<`.
	CompareLT CompareOp = iota
	// CompareLE is `<=`.
	CompareLE
	// CompareEQ is `==`.
	CompareEQ
	// CompareNE is `!=`.
	CompareNE
	// CompareGT is `>`.
	CompareGT
	// CompareGE is `>=`.
	CompareGE
)

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

func NewComplex(re, im float64) *Complex

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.

func (*Complex) Imag added in v0.10.1

func (c *Complex) Imag() float64

Imag returns the imaginary component.

func (*Complex) Real added in v0.10.1

func (c *Complex) Real() float64

Real returns the real component.

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

func NewCoroutine(name string) *Coroutine

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

func (c *Coroutine) Await() Object

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

func (c *Coroutine) Close() error

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)

func (*Coroutine) Send added in v0.10.1

func (c *Coroutine) Send(v Object) (Object, error)

Send drives the coroutine forward by one suspension point. The rules match Generator.Send: None on first call, otherwise an already-started coroutine receives the sent value.

CPython: Objects/genobject.c:L260 gen_send_ex2

func (*Coroutine) Throw added in v0.10.1

func (c *Coroutine) Throw(err error) (Object, error)

Throw raises err inside the coroutine at its await suspension.

CPython: Objects/genobject.c:L466 _gen_throw

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

func CoerceStarKwargs(o Object) (*Dict, error)

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

func FrameFastToLocals(f *Frame) (*Dict, error)

FrameFastToLocals returns a fresh dict that maps the frame's local names to their current values. The order matches CPython:

  1. fast locals (Code.Varnames)
  2. cell vars (Code.Cellvars)
  3. 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

func (d *Dict) Contains(key Object) (bool, error)

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

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

DelItem removes key. Mirrors PyDict_DelItem.

CPython: Objects/dictobject.c:2834 PyDict_DelItem

func (*Dict) GetItem

func (d *Dict) GetItem(key Object) (Object, error)

GetItem looks up key. Returns errKeyNotFound when absent.

CPython: Objects/dictobject.c:L1925 PyDict_GetItemWithError

func (*Dict) IsSplit added in v0.10.1

func (d *Dict) IsSplit() bool

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

func (d *Dict) ItemsView() Object

ItemsView returns a dict_items view over d.

CPython: Objects/dictobject.c:6674 dict_items_impl

func (*Dict) Keys added in v0.6.0

func (d *Dict) Keys() []Object

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

func (d *Dict) KeysView() Object

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

func (d *Dict) Len() int

Len returns the number of items.

CPython: Objects/dictobject.c:L3138 PyDict_Size

func (*Dict) SetItem

func (d *Dict) SetItem(key, value Object) error

SetItem inserts or replaces key. Mirrors PyDict_SetItem.

CPython: Objects/dictobject.c:1985 PyDict_SetItem

func (*Dict) ValuesView added in v0.10.1

func (d *Dict) ValuesView() Object

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

func NewEnumerate added in v0.10.1

func NewEnumerate(iterable Object, start *Int) (*Enumerate, error)

NewEnumerate wraps an iterable as enumerate(iterable, start). The iterable must expose a tp_iter slot.

CPython: Python/bltinmodule.c:1404 enum_new_impl

type ExceptionInstance added in v0.10.1

type ExceptionInstance interface {
	Object
	ExceptionType() *Type
	ExceptionArgs() *Tuple
}

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

func NewFile(f *os.File, name, mode string, binary, readable, writable bool) *File

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

func (fi *File) Close() error

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

func (fi *File) Flush() error

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

func (fi *File) Read(size int) (Object, error)

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

func (fi *File) Readline(size int) (Object, error)

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

func (fi *File) Write(o Object) (int, error)

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

type Filter struct {
	Header
	Func Object
	It   Object
}

Filter is filterobject.

CPython: Python/bltinmodule.c:493 filterobject

func NewFilter added in v0.10.1

func NewFilter(fn, iterable Object) (*Filter, error)

NewFilter mirrors filter_new: turn iterable into an iterator and pair it with the predicate. The predicate may be None to mean "use the truth protocol on each element directly".

CPython: Python/bltinmodule.c:501 filter_new

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

func FloatFromString(s string) (*Float, error)

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

func NewFloat

func NewFloat(x float64) *Float

NewFloat builds a float.

CPython: Objects/floatobject.c:L132 PyFloat_FromDouble

func (*Float) Float64

func (f *Float) Float64() float64

Float64 returns the underlying double.

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

func (f *Frame) Back() *Frame

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

func (f *Frame) Builtins() Object

Builtins returns f.f_builtins.

CPython: Objects/frameobject.c:888 frame_getbuiltins / 1346 PyFrame_GetBuiltins

func (*Frame) Code added in v0.10.1

func (f *Frame) Code() *Code

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

func (f *Frame) Globals() Object

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

func (f *Frame) Lasti() int

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

func (f *Frame) Lineno() int

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

func (f *Frame) SetTrace(fn Object)

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

func (f *Frame) SetTraceLines(v bool)

SetTraceLines stores f.f_trace_lines.

func (*Frame) SetTraceOpcodes added in v0.10.1

func (f *Frame) SetTraceOpcodes(v bool)

SetTraceOpcodes stores f.f_trace_opcodes.

func (*Frame) Trace added in v0.10.1

func (f *Frame) Trace() Object

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

func (f *Frame) TraceLines() bool

TraceLines reports f.f_trace_lines.

func (*Frame) TraceOpcodes added in v0.10.1

func (f *Frame) TraceOpcodes() bool

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

func NewFunction(name string, code *Code, globals Object) *Function

NewFunction is the no-qualname form of NewFunctionWithQualName.

CPython: Objects/funcobject.c:407 PyFunction_New

func NewFunctionWithQualName added in v0.10.1

func NewFunctionWithQualName(code *Code, globals Object, qualname string) (*Function, error)

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

func (f *Function) GetAnnotations() (*Dict, error)

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

func (f *Function) SetAnnotations(d *Dict)

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

func (f *Function) SetClosure(t *Tuple)

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

func (f *Function) SetCode(code *Code) error

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

func (f *Function) SetDefaults(t *Tuple)

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

func (f *Function) SetKwDefaults(d *Dict)

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

func NewGenerator(name string) *Generator

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

func (g *Generator) Close() error

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

func (g *Generator) Send(v Object) (Object, error)

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

func (*Generator) Throw added in v0.10.1

func (g *Generator) Throw(err error) (Object, error)

Throw raises err inside the generator at its current YIELD_VALUE suspension point. If the generator catches it and yields, that value is returned; if it propagates, Throw returns the error.

CPython: Objects/genobject.c:L466 _gen_throw

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

func (h *Header) Hdr() *Header

Hdr returns the receiver. Implements Object for any value that embeds *Header.

func (*Header) Init added in v0.3.0

func (h *Header) Init(t *Type)

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

func (*Header) Refcnt

func (h *Header) Refcnt() int64

Refcnt returns the current refcount. Test-only; production code should not depend on the exact value because Go's GC reclaims memory independently.

CPython: Include/object.h:L246 Py_REFCNT

func (*Header) Type

func (h *Header) Type() *Type

Type returns the type pointer stored in the header.

CPython: Include/object.h:L249 Py_TYPE

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

func NewInstance(t *Type) *Instance

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)

func (*Instance) Dict added in v0.10.1

func (i *Instance) Dict() *Dict

Dict returns the instance __dict__. Mutating it is how attribute stores land. Returns nil when the class declared __slots__ without __dict__.

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

func IntFromString(s string, base int) (*Int, error)

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

func NewInt(x int64) *Int

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

func NewIntFromBig(b *big.Int) *Int

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)

func (*Int) BigInt

func (i *Int) BigInt() *big.Int

BigInt returns a copy of the underlying big.Int.

func (*Int) Int64

func (i *Int) Int64() (val int64, ok bool)

Int64 returns the value as int64 if it fits; ok is false otherwise.

CPython: Objects/longobject.c:L666 PyLong_AsLongAndOverflow (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

type LineEntry struct {
	Start int
	End   int
	Line  int
}

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

func CoLines added in v0.5.5

func CoLines(c *Code) []LineEntry

CoLines projects CoPositions down to (start, end, line). The caller pays the column-decoding cost only when they need column data via CoPositions.

CPython: Objects/codeobject.c:1017 PyCode_Addr2Line (called per instruction range).

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

func MappingItems(o Object) (*List, error)

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

func MappingKeys(o Object) (*List, error)

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

func MappingValues(o Object) (*List, error)

MappingValues returns list(o.values()).

CPython: Objects/abstract.c:2477 PyMapping_Values

func NewList

func NewList(items []Object) *List

NewList builds a list from items. The slice is copied.

CPython: Objects/listobject.c:L156 PyList_New

func SequenceList added in v0.10.1

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

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

func (l *List) Append(v Object)

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

func (l *List) Copy() *List

Copy returns a shallow copy.

CPython: Objects/listobject.c:1248 list_copy

func (*List) Count added in v0.10.1

func (l *List) Count(value Object) (int, error)

Count returns the number of elements equal to value.

CPython: Objects/listobject.c:1502 list_count

func (*List) Index added in v0.10.1

func (l *List) Index(value Object, start, stop int) (int, error)

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

func (l *List) Insert(where int, value Object)

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

func (l *List) Item(i int) Object

Item returns the item at index i without bounds check.

CPython: Objects/listobject.c:L308 PyList_GetItem

func (*List) Len

func (l *List) Len() int

Len returns the number of items.

CPython: Objects/listobject.c:L286 PyList_Size

func (*List) Pop added in v0.10.1

func (l *List) Pop(i int) (Object, error)

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

func (l *List) Remove(value Object) error

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

func (l *List) SetSlice(start, stop int, values []Object)

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

func (l *List) Sort(keyfunc Object, reverse bool) (retErr error)

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 Map added in v0.10.1

type Map struct {
	Header
	Func   Object
	Iters  []Object
	Strict bool
}

Map is mapobject.

CPython: Python/bltinmodule.c:1351 mapobject

func NewMap added in v0.10.1

func NewMap(fn Object, iterables []Object, strict bool) (*Map, error)

NewMap mirrors map_new: convert each iterable to its iterator up front so we fail eagerly on a non-iterable argument.

CPython: Python/bltinmodule.c:1361 map_new

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

const (
	MethVarargs  MethFlag = 1 << 0
	MethKeywords MethFlag = 1 << 1
	MethNoArgs   MethFlag = 1 << 2
	MethO        MethFlag = 1 << 3
	MethClass    MethFlag = 1 << 4
	MethStatic   MethFlag = 1 << 5
	MethCoexist  MethFlag = 1 << 6
	MethFastcall MethFlag = 1 << 7
	MethMethod   MethFlag = 1 << 9
)

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

func NewModule(name string) *Module

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

func (m *Module) Dict() *Dict

Dict returns the module's attribute dict (__dict__).

CPython: Objects/moduleobject.c:459 PyModule_GetDict

func (*Module) SetState added in v0.8.0

func (m *Module) SetState(s any)

SetState stores a per-module state value.

CPython: Objects/moduleobject.c:486 PyModule_SetState (gopy analog)

func (*Module) State added in v0.8.0

func (m *Module) State() any

State returns the per-module state pointer set by Go-implemented modules.

CPython: Objects/moduleobject.c:476 PyModule_GetState

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

func (*Namespace) Dict added in v0.10.1

func (n *Namespace) Dict() *Dict

Dict returns the namespace's underlying attribute dict.

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

func Call(callable Object, args *Tuple, kwargs *Dict) (Object, error)

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

func CallNoArgs(callable Object) (Object, error)

CallNoArgs is PyObject_CallNoArgs; a zero-arg vectorcall.

CPython: Objects/call.c:101 PyObject_CallNoArgs

func CallObject added in v0.6.0

func CallObject(callable Object, args *Tuple) (Object, error)

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

func CallOneArg(callable Object, arg Object) (Object, error)

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

func CallPrepend(callable Object, obj Object, args *Tuple, kwargs *Dict) (Object, error)

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

func GenericGetAttr(o Object, name Object) (Object, error)

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

func GetAttr(o Object, name Object) (Object, error)

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

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

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

func InternFromString(s string) Object

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

func Iter(o Object) (Object, error)

Iter returns iter(o). Mirrors PyObject_GetIter.

CPython: Objects/abstract.c:2786 PyObject_GetIter

func IterNext added in v0.10.1

func IterNext(o Object) (Object, error)

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

func MakeTpCall(callable Object, args []Object, nargs int, keywords Object) (Object, error)

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

func MappingGetItemString(o Object, key string) (Object, error)

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

func MappingGetOptionalItem(o, key Object) (Object, bool, error)

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

func MappingGetOptionalItemString(o Object, key string) (Object, bool, error)

MappingGetOptionalItemString is the string-key form of MappingGetOptionalItem.

CPython: Objects/abstract.c:2316 PyMapping_GetOptionalItemString

func NewBool

func NewBool(b bool) Object

NewBool returns the True or False singleton. Mirrors PyBool_FromLong.

CPython: Objects/boolobject.c:L33 PyBool_FromLong

func NewStr added in v0.3.0

func NewStr(s string) Object

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

func NumberAbsolute(o Object) (Object, error)

NumberAbsolute is abs(o).

CPython: Objects/abstract.c:1384 PyNumber_Absolute

func NumberAdd added in v0.10.1

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

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 NumberAnd added in v0.10.1

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

NumberAnd is a & b.

CPython: Objects/abstract.c:1121 PyNumber_And

func NumberDivmod added in v0.10.1

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

NumberDivmod is divmod(a, b).

CPython: Objects/abstract.c:1125 PyNumber_Divmod

func NumberFloorDivide added in v0.10.1

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

NumberFloorDivide is a // b.

CPython: Objects/abstract.c:1185 PyNumber_FloorDivide

func NumberInPlaceAdd added in v0.10.1

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

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

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

NumberInPlaceAnd is a &= b.

CPython: Objects/abstract.c:1287 PyNumber_InPlaceAnd

func NumberInPlaceFloorDivide added in v0.10.1

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

NumberInPlaceFloorDivide is a //= b.

CPython: Objects/abstract.c:1292 PyNumber_InPlaceFloorDivide

func NumberInPlaceLshift added in v0.10.1

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

NumberInPlaceLshift is a <<= b.

CPython: Objects/abstract.c:1288 PyNumber_InPlaceLshift

func NumberInPlaceMatrixMultiply added in v0.10.1

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

NumberInPlaceMatrixMultiply is a @= b.

CPython: Objects/abstract.c:1291 PyNumber_InPlaceMatrixMultiply

func NumberInPlaceMultiply added in v0.10.1

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

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

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

NumberInPlaceOr is a |= b.

CPython: Objects/abstract.c:1285 PyNumber_InPlaceOr

func NumberInPlacePower added in v0.10.1

func NumberInPlacePower(a, b, mod Object) (Object, error)

NumberInPlacePower is a **= b.

CPython: Objects/abstract.c:1349 PyNumber_InPlacePower

func NumberInPlaceRemainder added in v0.10.1

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

NumberInPlaceRemainder is a %= b.

CPython: Objects/abstract.c:1294 PyNumber_InPlaceRemainder

func NumberInPlaceRshift added in v0.10.1

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

NumberInPlaceRshift is a >>= b.

CPython: Objects/abstract.c:1289 PyNumber_InPlaceRshift

func NumberInPlaceSubtract added in v0.10.1

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

NumberInPlaceSubtract is a -= b.

CPython: Objects/abstract.c:1290 PyNumber_InPlaceSubtract

func NumberInPlaceTrueDivide added in v0.10.1

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

NumberInPlaceTrueDivide is a /= b.

CPython: Objects/abstract.c:1293 PyNumber_InPlaceTrueDivide

func NumberInPlaceXor added in v0.10.1

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

NumberInPlaceXor is a ^= b.

CPython: Objects/abstract.c:1286 PyNumber_InPlaceXor

func NumberIndex added in v0.10.1

func NumberIndex(o Object) (Object, error)

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

func NumberInvert(o Object) (Object, error)

NumberInvert is ~o.

CPython: Objects/abstract.c:1383 PyNumber_Invert

func NumberLshift added in v0.10.1

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

NumberLshift is a << b.

CPython: Objects/abstract.c:1122 PyNumber_Lshift

func NumberMatrixMultiply added in v0.10.1

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

NumberMatrixMultiply is a @ b.

CPython: Objects/abstract.c:1184 PyNumber_MatrixMultiply

func NumberMultiply added in v0.10.1

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

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

func NumberNegative(o Object) (Object, error)

NumberNegative is -o.

CPython: Objects/abstract.c:1381 PyNumber_Negative

func NumberOr added in v0.10.1

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

NumberOr is a | b.

CPython: Objects/abstract.c:1119 PyNumber_Or

func NumberPositive added in v0.10.1

func NumberPositive(o Object) (Object, error)

NumberPositive is +o.

CPython: Objects/abstract.c:1382 PyNumber_Positive

func NumberPower added in v0.10.1

func NumberPower(a, b, mod Object) (Object, error)

NumberPower is pow(a, b, mod). mod may be nil.

CPython: Objects/abstract.c:1190 PyNumber_Power

func NumberRemainder added in v0.10.1

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

NumberRemainder is a % b.

CPython: Objects/abstract.c:1187 PyNumber_Remainder

func NumberRshift added in v0.10.1

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

NumberRshift is a >> b.

CPython: Objects/abstract.c:1123 PyNumber_Rshift

func NumberSubtract added in v0.10.1

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

NumberSubtract is a - b.

CPython: Objects/abstract.c:1124 PyNumber_Subtract

func NumberTrueDivide added in v0.10.1

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

NumberTrueDivide is a / b.

CPython: Objects/abstract.c:1186 PyNumber_TrueDivide

func NumberXor added in v0.10.1

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

NumberXor is a ^ b.

CPython: Objects/abstract.c:1120 PyNumber_Xor

func RichCmp

func RichCmp(a, b Object, op CompareOp) (Object, error)

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

func SequenceConcat(s, o Object) (Object, error)

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

func SequenceFast(v Object, m string) (Object, error)

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

func SequenceGetItem(s Object, i int) (Object, error)

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

func SequenceInPlaceConcat(s, o Object) (Object, error)

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

func SequenceInPlaceRepeat(s Object, count int) (Object, error)

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

func SequenceRepeat(s Object, count int) (Object, error)

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

func TypeOf(o Object) Object

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

func Vectorcall(callable Object, args []Object, nargsf uint, kwnames *Tuple) (Object, error)

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

func VectorcallDict(callable Object, args []Object, nargsf uint, kwargs *Dict) (Object, error)

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

type PositionEntry struct {
	Start     int
	End       int
	Line      int
	EndLine   int
	Column    int
	EndColumn int
}

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

func NewProperty(fget, fset, fdel, doc Object) *Property

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

func (p *Property) Deleter(fdel Object) *Property

Deleter returns a copy of p with fdel replaced. Powers the @prop.deleter decorator.

CPython: Objects/descrobject.c:1695 property_deleter

func (*Property) Getter added in v0.10.1

func (p *Property) Getter(fget Object) *Property

Getter returns a copy of p with fget replaced. Powers the @prop.getter decorator.

CPython: Objects/descrobject.c:1683 property_getter

func (*Property) Setter added in v0.10.1

func (p *Property) Setter(fset Object) *Property

Setter returns a copy of p with fset replaced. Powers the @prop.setter decorator.

CPython: Objects/descrobject.c:1689 property_setter

type Range

type Range struct {
	Header
	Start *Int
	Stop  *Int
	Step  *Int
}

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

func NewRange

func NewRange(start, stop, step *Int) (*Range, error)

NewRange builds a range. Step must be non-zero.

CPython: Objects/rangeobject.c:L92 range_from_array

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

func NewReversed(seq Object) (*Reversed, error)

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

func NewSeqIter(seq Object) *SeqIter

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

func NewFrozenset(items []Object) (*Set, error)

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

func (s *Set) Add(key Object) error

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

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

Contains reports whether key is in the set.

CPython: Objects/setobject.c:L1777 set_contains_key

func (*Set) Difference added in v0.10.1

func (s *Set) Difference(others ...*Set) (*Set, error)

Difference returns self \ ⋃others.

CPython: Objects/setobject.c:1750 set_difference_multi

func (*Set) Discard added in v0.8.0

func (s *Set) Discard(key Object) error

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

func (s *Set) Intersection(others ...*Set) (*Set, error)

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

func (s *Set) IsDisjoint(other *Set) (bool, error)

IsDisjoint reports whether self and other share no elements.

CPython: Objects/setobject.c:2185 set_isdisjoint

func (*Set) IsSubset added in v0.10.1

func (s *Set) IsSubset(other *Set) (bool, error)

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

func (s *Set) IsSuperset(other *Set) (bool, error)

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

func (s *Set) Items() []Object

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

func (s *Set) Len() int

Len returns the number of items.

CPython: Objects/setobject.c:L2201 PySet_Size

func (*Set) SymmetricDifference added in v0.10.1

func (s *Set) SymmetricDifference(other *Set) (*Set, error)

SymmetricDifference returns self △ other: items in exactly one of the two operands.

CPython: Objects/setobject.c:1881 set_symmetric_difference

func (*Set) Union added in v0.10.1

func (s *Set) Union(others ...*Set) (*Set, error)

Union returns self ∪ others. The result borrows self's mutability (set if self is a set, frozenset if self is a frozenset).

CPython: Objects/setobject.c:1448 set_union

func (*Set) Update added in v0.10.1

func (s *Set) Update(others ...*Set) error

Update folds others into self in place. Errors when self is frozen.

CPython: Objects/setobject.c:1330 set_update_internal

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

type Slice struct {
	Header
	Start Object
	Stop  Object
	Step  Object
}

Slice is the Python slice object: start, stop, step.

CPython: Include/cpython/sliceobject.h:L8 PySliceObject

func NewSlice

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

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

func (s *Slice) GetIndices(length int) (start, stop, step, slicelen int, err error)

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

func (s *Slice) Indices(length int) (Object, error)

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

func (*Slice) Unpack added in v0.10.1

func (s *Slice) Unpack() (start, stop, step int, err error)

Unpack pulls (start, stop, step) out of the slice as concrete ints. Step defaults to 1 and may not be zero. Start/stop default to the step-aware extremes (0/MAX for forward, MAX/MIN for backward).

CPython: Objects/sliceobject.c:218 PySlice_Unpack

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

func NewStructSeq(tp *Type, values []Object) *StructSeq

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

func (s *StructSeq) AsTuple() *Tuple

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)

func (*StructSeq) Items added in v0.10.1

func (s *StructSeq) Items() []Object

Items returns the underlying slice. Callers must not mutate it.

type StructSeqField added in v0.10.1

type StructSeqField struct {
	Name string
	Doc  string
}

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

func NewSuper(typ *Type, obj Object) (*Super, error)

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

func CoerceStarArgs(o Object) (*Tuple, error)

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

func NewTuple(items []Object) *Tuple

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

func SequenceTuple(v Object) (*Tuple, error)

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

func (t *Tuple) Count(value Object) (int, error)

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

func (t *Tuple) Index(value Object, start, stop int) (int, error)

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

func (*Tuple) Item

func (t *Tuple) Item(i int) Object

Item returns the item at index i. No bounds check; callers are expected to clamp.

CPython: Objects/tupleobject.c:L319 PyTuple_GetItem

func (*Tuple) Len

func (t *Tuple) Len() int

Len returns the number of items.

CPython: Objects/tupleobject.c:L296 PyTuple_Size

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

func NewType(name string, bases []*Type) *Type

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

func NewUserType(name string, bases []*Type, ns *Dict) *Type

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

func StrType added in v0.3.0

func StrType() *Type

StrType returns the type singleton for str.

CPython: Objects/unicodeobject.c:L15188 PyUnicode_Type

func TypeType

func TypeType() *Type

TypeType returns the type singleton for `type` itself. Mirrors PyType_Type.

CPython: Objects/typeobject.c:L6361 PyType_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) IsASCII added in v0.10.1

func (s *Unicode) IsASCII() bool

IsASCII reports whether every code point is < 0x80.

func (*Unicode) IsReady added in v0.10.1

func (s *Unicode) IsReady() bool

IsReady reports whether the canonical layout is built. Always true for strings created via NewStr.

func (*Unicode) Kind added in v0.10.1

func (s *Unicode) Kind() byte

Kind returns the PEP 393 kind tag.

func (*Unicode) Length added in v0.10.1

func (s *Unicode) Length() int

Length returns the number of code points.

func (*Unicode) Value added in v0.10.1

func (s *Unicode) Value() string

Value returns the canonical Go string. Same-package callers may also read s.v directly; this getter exists for cross-package use.

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

func (*VarHeader) Size

func (v *VarHeader) Size() int64

Size returns ob_size. Only meaningful for VarHeader-backed types.

CPython: Include/object.h:L252 Py_SIZE

type Visitor added in v0.10.0

type Visitor func(Object) error

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

func NewWeakCallableProxy(referent, callback Object) *WeakProxy

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

func NewWeakProxy(referent, callback Object) *WeakProxy

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

func (*WeakProxy) Callback added in v0.10.1

func (p *WeakProxy) Callback() Object

Callback returns the registered callback (or None).

func (*WeakProxy) Clear added in v0.10.1

func (p *WeakProxy) Clear() Object

Clear drops the referent. Returns the callback for the caller to invoke, or None when no callback was installed. Idempotent.

CPython: Objects/weakrefobject.c:107 clear_weakref

func (*WeakProxy) Referent added in v0.10.1

func (p *WeakProxy) Referent() Object

Referent returns the live target or nil when the proxy has been cleared.

CPython: Objects/weakrefobject.c:191 PyWeakref_GetObject

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

func NewWeakref(referent, callback Object) *Weakref

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

func (w *Weakref) Callback() Object

Callback returns the registered callback, or None if none was set.

func (*Weakref) Clear added in v0.10.0

func (w *Weakref) Clear() Object

Clear drops the referent. Returns the callback (or None if there is none); the caller is responsible for invoking it. Idempotent; repeated calls return None.

CPython: Objects/weakrefobject.c:107 clear_weakref

func (*Weakref) Referent added in v0.10.0

func (w *Weakref) Referent() Object

Referent returns the live target or None if the weakref has been cleared. Concurrent-safe.

CPython: Objects/weakrefobject.c:191 PyWeakref_GetObject

Jump to

Keyboard shortcuts

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