objects

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: May 6, 2026 License: Apache-2.0 Imports: 8 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 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 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 CellType = NewType("cell", []*Type{objectType})

CellType is the type singleton for cell objects.

CPython: Objects/cellobject.c PyCell_Type

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

CodeType is the type singleton for code objects.

CPython: Objects/codeobject.c PyCode_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 ErrStopIteration = errors.New("StopIteration")

ErrStopIteration signals end of iteration. Mirrors PyExc_StopIteration.

CPython: Objects/exceptions.c:L1937 PyExc_StopIteration

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 PyFunction_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 ModuleType = NewType("module", []*Type{objectType})

ModuleType is the type singleton for module objects.

CPython: Objects/moduleobject.c:766 PyModule_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 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 TupleType = NewType("tuple", []*Type{objectType})

TupleType is the type singleton for tuple. Mirrors PyTuple_Type.

CPython: Objects/tupleobject.c:L961 PyTuple_Type

Functions

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 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 Incref

func Incref(o Object)

Incref bumps the refcount. Concurrent Increfs are safe.

CPython: Include/object.h:L605 Py_INCREF

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 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 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 IsTruthy

func IsTruthy(o Object) (bool, error)

IsTruthy mirrors PyObject_IsTrue.

CPython: Objects/object.c:L1671 PyObject_IsTrue

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 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 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 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 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 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 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 Code added in v0.5.5

type Code struct {
	Header

	// Argument shape. CPython sets all four counts at compile time;
	// the interpreter reads them when binding a CALL_FUNCTION.
	Argcount        int
	PosonlyArgcount int
	KwonlyArgcount  int
	Stacksize       int

	// Flags carries the CO_* bitset (CO_OPTIMIZED, CO_NEWLOCALS,
	// CO_VARARGS, CO_VARKEYWORDS, CO_NESTED, CO_GENERATOR,
	// CO_COROUTINE, CO_ASYNC_GENERATOR, etc.).
	Flags int

	// Code is the bytecode blob. Each instruction is a 16-bit
	// (op, arg) pair; the interpreter dispatch loop walks it.
	Code []byte

	// Consts is the literal table the LOAD_CONST opcode indexes into.
	Consts []any

	// Names, Varnames, Freevars, Cellvars are name tables indexed
	// by their respective LOAD_/STORE_ opcodes.
	Names    []string
	Varnames []string
	Freevars []string
	Cellvars []string

	// Filename, Name, Qualname mirror co_filename / co_name /
	// co_qualname. The traceback renderer reads them.
	Filename string
	Name     string
	Qualname string

	// Firstlineno is the source line of the first statement in
	// the code; the linetable encodes deltas from this anchor.
	Firstlineno int

	// Linetable is the PEP 626 location table. Decoded via
	// CoLines / CoPositions in code_tables.go.
	Linetable []byte

	// ExceptionTable is the compact try/except table the
	// interpreter walks on RAISE_VARARGS / END_FINALLY.
	ExceptionTable []byte
}

Code is the AST -> bytecode handoff value. Compile produces one of these per code-bearing node (module, function body, class body, comprehension).

CPython: Include/internal/pycore_code.h:115 _PyCodeObject

func NewCode added in v0.6.0

func NewCode() *Code

NewCode returns a Code with its header bound to CodeType.

type 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 Dict

type Dict struct {
	Header
	// contains filtered or unexported fields
}

Dict is the Python dict.

CPython: Include/cpython/dictobject.h:L19 PyDictObject

func NewDict

func NewDict() *Dict

NewDict builds an empty dict.

CPython: Objects/dictobject.c:L765 PyDict_New

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

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

DelItem removes key. Mirrors PyDict_DelItem.

CPython: Objects/dictobject.c:L2154 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) 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) 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:L1985 PyDict_SetItem

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 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 Function added in v0.6.0

type Function struct {
	Header
	Name       string
	Qualname   string
	Code       *Code
	Globals    Object
	Defaults   *Tuple // positional defaults, may be nil
	KwDefaults *Dict  // keyword-only defaults, may be nil
	Closure    *Tuple // tuple of cells, may be nil
}

Function is a Python-defined function: a code object plus the captured globals, defaults, and closure cells. The runtime call arm pushes a new frame off the bound code, threads the callable's globals through to the frame's f_globals, and dispatches.

v0.6 holds Code as Object so we don't need to import frame here; the call site does the type-check.

CPython: Include/cpython/funcobject.h PyFunctionObject

func NewFunction added in v0.6.0

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

NewFunction builds a function from a code object plus its globals. Defaults / closure can be set on the returned value before exposing it.

CPython: Objects/funcobject.c PyFunction_New

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 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 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 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 NewList

func NewList(items []Object) *List

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

CPython: Objects/listobject.c:L156 PyList_New

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

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

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 False

func False() Object

False returns the False singleton. Mirrors Py_False.

CPython: Include/object.h:L857 Py_False

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 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 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 the v0.3 placeholder str object. The real unicodeobject port (v0.4) will replace this with a kind/length/data layout that matches CPython's compact-string representation.

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 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 True

func True() Object

True returns the True singleton. Mirrors Py_True.

CPython: Include/object.h:L860 Py_True

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)

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

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

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

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 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 (*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
	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)
	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
	Dealloc  func(o Object)

	Number   *NumberMethods
	Sequence *SequenceMethods
	Mapping  *MappingMethods
}

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

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

Jump to

Keyboard shortcuts

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