Skip to content

Built-in functions

Monty implements a subset of CPython’s builtins. Referencing any name not listed here raises NameError at runtime; there is no fallback to a host Python.

Implemented builtin functions

abs, all, any, bin, chr, divmod, enumerate, eval, exec, filter, format, getattr, hasattr, hash, hex, id, isinstance, iter, len, locals, map, max, min, next, oct, open, ord, pow, print, repr, reversed, round, setattr, sorted, sum, type, zip. eval, exec and locals are described in eval_exec.md.

Implemented type constructors (also builtins)

bool, bytes, complex, dict, float, frozenset, int, list, range, set, slice, str, tuple. Exception classes (ValueError, TypeError, etc.) are also names in the builtin namespace.

Builtins that are NOT implemented

These raise NameError:

  • Code objects and imports: compile, __import__.
  • Namespace introspection: globals, vars, dir.
  • Interactive: input, breakpoint, help.
  • Decorators / descriptors: classmethod, staticmethod, property. (@property on functions is not recognized; use a method.)
  • Construction / coercion: bytearray, memoryview, object, ascii.
  • Inheritance: super; call the base explicitly (Base.__init__(self, ...)).
  • Other: callable, delattr, aiter, anext.

object exists as the root class but cannot be instantiated, and issubclass() works on classes; see classes.md.

Behavioural divergences

  • No __class__ on builtin values — [].__class__, list.__class__ and list[int].__class__ raise AttributeError; only instances of Monty classes carry it (see classes.md). Use type(x).
  • Builtin methods are call-only — reading one without calling it raises AttributeError, so [1].append, 'a'.upper, {}.get, dict.fromkeys and list.__class_getitem__ cannot be assigned, passed as a callback or reached through getattr. Call them directly (list.__class_getitem__(int)).
  • Large integer literal identity — separate occurrences of the same literal outside the i64 range are not deduplicated, so a = 18446744073709551616; b = 18446744073709551616; a is b is False where CPython may reuse a single constant and return True. Repeated loads of one literal share its identity; use == to compare numeric values.
  • hash(x) — Monty hashes str, bytes, float, complex and every container with its own algorithm, so the values differ from CPython’s. Only bool, small int, and a float or complex equal to one of them agree: an int hashes to itself, which is what CPython does while abs(x) < 2**61 - 1, but CPython reduces modulo 2**61 - 1 from there up (hash(2**62) is 2 in CPython, 4611686018427387904 in Monty) and Monty hashes an int too large for an i64 differently again. Monty’s hashes are stable within a run and across runs of the same build (there is no hash randomisation), but never persist one or compare one against a CPython hash. sys.hash_info is not exposed, so the parameters CPython publishes are unavailable (see sys.md).
  • a set iterated while it is mutated may yield a newly added element — Monty’s sets keep insertion order, so an element added during iteration is appended after the cursor and gets yielded. CPython places it by hash, which can put it behind the cursor and out of that walk’s reach. Both engines raise RuntimeError: Set changed size during iteration when the size changes; this is only about which walk sees a same-size replacement. Monty also stops a set walk once it has yielded the set’s starting length, where CPython keeps going: replacing each element as it is visited yields every replacement in CPython but only the original elements in Monty.
  • is and id() on short strings — equal strings of 2–15 UTF-8 bytes stored inline share identity by content. Separate runtime results such as bin(4) can therefore compare identical and return the same id(), where CPython gives those results distinct identities.
  • Some dict copies re-hash the keys — CPython copies the hash table for {**d} and copy.copy(d) without calling a key’s __hash__. Monty re-inserts each pair, so a key with a custom __hash__ sees it called again — observable through a counter or other side effect, and a __hash__ that raises makes the copy fail where CPython’s succeeds. dict(d), defaultdict(factory, d), d.copy() and Counter.copy() reuse stored hashes and run no key callbacks while copying entries. An empty Counter receiving a dict’s counts also uses this path; keyword arguments are applied afterward. See copy.md for copy.copy. set.copy() clones the storage directly, and frozenset(f) returns f unchanged when f is already a frozenset; neither re-hashes its elements.
  • Equality callbacks while copying dicts — Monty’s cached-hash copies preserve live entries without calling key __eq__ methods. CPython may compare keys when rebuilding a sparse table after deletions; such a callback can raise or change which keys survive in the copy there.
  • dict/set lookups under a mutating __eq__ — like CPython, a lookup (in, d[k], set.remove, …) whose user __eq__ mutates the container keeps probing rather than raising, and a mutation that only adds colliding keys never makes it repeat a comparison. Monty re-reads the colliding candidates after each comparison where CPython walks the live probe chain, so an __eq__ that moves the entry being compared restarts the probe and re-compares the other candidates from scratch — extra __eq__ calls CPython would not make (CPython restarts and re-compares too, but only after a resize or when that entry’s own slot changed). An __eq__ that adds a colliding key on every comparison never finishes in either engine; under a duration limit Monty raises TimeoutError. No mutation pattern can panic or corrupt either engine.
  • Set algebra under a mutating __eq__ — -, &, ^, in-place intersection (&=), and their method forms walk one of the two sets while user __eq__ code can run. Monty raises RuntimeError: Set changed size during iteration if that code adds or removes an element from the set being walked, where CPython carries on over its live table and returns a result. The operand Monty is not walking is snapshotted before the operation begins, so mutating that one is never observed at all — s | t and t.update(s) see all of s’s original elements even when __eq__ clears s partway through, where CPython’s merge stops early. A mutation that empties the set being probed rather than walked is a resize to neither engine, but they still answer from different sides of it: with s’s own __eq__ clearing s, s.isdisjoint(t) is False in Monty, which keeps the comparison that matched, and True in CPython, which restarts the probe and finds the set empty. In-place |=, -=, ^=, and &= also snapshot their right operand before mutation. Changes to that operand made by user __eq__ are not observed.
  • Dict-view set operators re-hash the view’s own keys — d.keys() - s, |, ^ and their reflected forms collect those keys through a live, resize-checked walk that calls __hash__ on each one. CPython probes with each key’s stored hash and mostly does not call it at all. So a __hash__ — or a colliding __eq__ — that resizes the dict raises RuntimeError: dictionary changed size during iteration in Monty where CPython completes, as in d.keys() - s; CPython raises too wherever its own walk observes the change, as in s - d.keys() and d.items() - s. The operand that is not the view is snapshotted before these operators begin, so mutating that one is never observed. Absent mutation every result agrees. & and isdisjoint walk and probe the same operands as CPython, set-to-set operators do not re-hash at all, and dict-view equality (d.keys() == s) raises exactly where CPython does.
  • enumerate, zip and reversed are eager, not lazy — each returns a list, so type(enumerate(x)).__name__ is 'list' rather than 'enumerate'. The whole result is held in memory, and enumerate(itertools.count()) never returns until a resource limit trips. Results can be indexed and re-iterated, unlike CPython’s iterators. Mutating the source from inside the loop body is not observed, so dict, set and collections.deque do not report mutation during iteration through these builtins. zip stops at the shortest input, so pairing an infinite iterable with a finite or empty one stays bounded. See itertools.md.
  • map and filter callbacks cannot suspend through synchronous consumers, such as list(map(f, xs)). Use a comprehension or explicit next() when the callback needs to call the host. Their iterator attributes have the restrictions listed in iter.md.
  • Arity-error wording for some str/bytes methods — a handful of keyword-accepting methods (e.g. str.split, str.rsplit and the bytes equivalents) report too-many-arguments as split expected at most 2 arguments, got 3, where CPython 3.14’s Argument Clinic pre-counts positionals plus kwargs and says split() takes at most 2 arguments (3 given). Methods audited against CPython (encode, decode, expandtabs, splitlines, replace, …) already match; the remainder need a per-function at_most_total audit.
  • getattr(obj, name) — if the resolved attribute would be an async coroutine, external function, or OS call, raises TypeError: "getattr(): attribute is not a simple value" rather than returning a bound method object. Use direct attribute access (obj.name(...)) for these.
  • int(x, base=10) — string/bytes parsing accepts ASCII digits only; CPython also accepts non-ASCII Unicode decimal digits (int('١٢') == 12), which Monty rejects with invalid literal for int() with base 10.
  • float(x) — string parsing accepts ASCII digits only; CPython also accepts Unicode decimal digits (float('١.٥') == 1.5), which Monty rejects with could not convert string to float.
  • slice — slice bounds and the length argument to slice.indices(length) are saturated to i64::MIN/i64::MAX when outside the i64 range; sequence lengths are represented as usize.
  • isinstance(obj, T) — T must be a built-in type (int, str, list, …), a built-in exception class, a sandbox-defined class (see classes.md), a | union of those (see typing.md), or a tuple of those. Passing a host-supplied dataclass / namedtuple as the second argument raises TypeError.
  • iter() — see iter.md for iterator and iter(callable, sentinel) divergences.
  • pow(base, exp, mod) with integer operands rejects negative exponents with ValueError instead of computing a modular inverse. Non-modular exponents whose result cannot be materialized raise OverflowError (see resource_limits.md).
  • pow(base, exp) and ** with float operands and a real result — overflow raises OverflowError like CPython, always worded (34, 'Numerical result out of range') (glibc’s strerror(ERANGE); CPython on macOS and Windows says (34, 'Result too large')), and exc.args is that text as one string rather than CPython’s (34, '...') tuple.
  • sorted(iterable, *, key=None, reverse=False) — key and reverse must be passed by keyword; positional forms raise TypeError.
  • round(n, ndigits) for an int n — ndigits values outside the i64 range are clamped by sign. For a hugely negative ndigits, CPython tries to materialise 10**-ndigits and dies with MemoryError where Monty returns 0 immediately.
  • print — writes via the host print callback. file=, flush= are not honoured; sep= and end= are.
  • Identity of host-supplied callables — host functions passed in as inputs (MontyObject::function(...)) lose their host object identity at the sandbox boundary. Live external functions are identified by lookup name, so distinct host callables with the same name share is, equality, id(), and hash() results. Once the last sandbox reference is dropped, a later conversion of that name may create a new function object.
  • Type objects across the host boundary — a type object (a class, not an instance) round-trips in both directions.
    • Sandbox → host (external/OS-call argument, or a .run() return value): the type is reconstructed as the corresponding host class. Genuine builtins (int, str, type, bytes, list, dict, property, …) resolve to the real builtin; Monty’s modeled stdlib types map to their host stdlib class: datetime/date/timedelta/timezone → datetime.*, re.Pattern/re.Match → re.*, the binary/text file types → io.*. The pathlib.Path class maps to pathlib.PurePosixPath, consistent with how Path instances round-trip, and instantiable on every host OS. A type with no faithful host class (e.g. an internal function or cell type) cannot be reconstructed and surfaces as an AttributeError from the host call.
    • Host → sandbox (input, or an external-call return value): the same recognized builtins and modeled stdlib types are preserved as type objects, so isinstance(x, the_type) works inside the sandbox. Recognition is by type-object identity, not class name/module, so a class that forges __name__/__module__ to impersonate a builtin is not treated as one. Every pathlib path class collapses to PurePosixPath (it re-emerges as PurePosixPath). A host class Monty does not model (e.g. a user-defined class) is not preserved as a type; it degrades to a callable, appearing inside the sandbox as a function rather than a type.