Lists, dicts, and sets¶
Python's own list, dict, and set lower to native code. A function that
builds and uses them goes native under ppy run, in a standalone binary, and
in emitted C and C++, with no rewrite to the ppy collections
and the same answers as CPython.
def busiest(lines: list[str]) -> str:
hits: dict[str, int] = {}
for line in lines:
path = line.split()[1]
hits[path] = hits.get(path, 0) + 1
best, most = "", 0
for path, count in hits.items():
if count > most:
best, most = path, count
return best
Natively a list is a sequence of the collections runtime, a dict a hash map
kept in insertion order, and a set a hash set. They are the same memory as a
ppy.Vec, ppy.HashMap, and ppy.HashSet: counted references, cycles
collected, freed when the last reference goes. The ppy types stay the
explicit way to say which structure you mean; a plain container gets the one
Python's container behaves like.
What lowers¶
A container's element, or a dict's value, is a number, a string, a number
or string that may be None, a tuple of numbers, a value class or an
object class, or another container: list[list[int]],
dict[str, list[int]], list[tuple[int, float]], list[int | None],
dict[str, str | None]. A key
of a dict or a set is an int, a str, a tuple of int, or an instance of
a class Python can hash (see Collections).
| displays | [a, b], {k: v}, {a, b}, and [], {}, set() given a type by the name they go to |
| repetition | [0] * n, [[0] * n for _ in range(m)] |
| comprehensions | [e for x in xs if c], {k: v for ...}, {e for ...}, nested, with the comprehension's names its own, and a generator given to sum, min, or max |
| constructors | list(xs), set(xs), dict(d) |
| a list | xs[i] and xs[i] = v from either end, slices with steps, append, extend, insert, pop(), pop(i), remove, index, count, sort() with key= and reverse=, reverse, clear, copy, del xs[i], + |
| a dict | d[k], d[k] = v, del d[k], get(k), get(k, default), setdefault, pop(k), pop(k, default), keys(), values(), items(), update, copy, clear |
| a set | add, remove, discard, update, copy, clear, \|, &, -, ^ and their methods, issubset, issuperset, isdisjoint |
| any of them | len, in, ==, if xs:, for loops, sorted, min, max, sum, any, all, enumerate, zip, reversed |
A value is evaluated before the slot it goes into is made, as Python
evaluates it, so xs.append(len(xs)) appends the length before the append.
Where a check fails, the call hands back to Python under ppy run, which
raises what CPython raises. A standalone binary prints CPython's last line
(IndexError: list index out of range, KeyError: 3,
ValueError: list.remove(x): x not in list, IndexError: pop from empty
list) and exits with status 1.
Aliases¶
Two names for one list are one list natively too: after b = a,
b.append(1) changes a, and row = grid[0] is the row inside grid.
[[0] * n] * m repeats one row m times, as in Python. A write through an
element lands in what the root name holds, so the compiler knows whether a
function writes only what it made or what it was passed.
The order of a set¶
CPython walks a set in the order its hash table keeps. For a set of ints or
of tuples of ints that order follows from the values and from what was done
to the set, and native code keeps a copy of CPython's table beside its own:
the same slots, the same probing, the same resizes, and the same algorithms
for |, &, -, ^, their in-place forms, update, copy, and pop.
So a for loop over such a set, list(s), a comprehension over it, s.pop(),
and printing it are native and give what CPython gives:
def pairs(n: int) -> set[tuple[int, int]]:
return {(i % 7, i * 31 % 11) for i in range(n)}
def shown(n: int) -> str:
s = pairs(n)
s -= {(0, 0)}
return f"{s} {s.pop()}"
A set made in Python and passed in has no such copy: its order is not known
natively, so a walk that shows it falls back to Python. A string's hash
changes from one process to the next unless PYTHONHASHSEED is fixed, so a
set of strings walked where its order shows stays in Python. What does not
depend on the order is native for every set: len, in, the set algebra,
sorted(s), min, max, sum, any, all.
A dict walks in insertion order, in Python and natively.
Between functions¶
A native function takes and returns containers by handle when native code calls it. A list of numbers that a function only reads is lent to it as a buffer, which native code and Python both pass without copying the elements; a list it writes, and every other container, goes by handle.
When Python calls such a function, the generated wrapper copies each
container argument into native memory and copies the result out as a new
list, dict, or set. After a call that writes through a parameter,
every container that came in with a parameter it writes is copied back into
the caller's object, which stays the same object. That includes one the call
took out of its parent: after row = g[0]; row.append(1); g.pop(0) the
caller's row has the 1, as in CPython. Of a list of numbers, only the
elements the call changed are set again; the others keep their identity, as
does any element the call left as it was. An argument whose contents do not
match the declared type runs the Python body instead.
Each object is copied once however often it is reached, and comes back as
one object: f(xs, xs) writes one list, the rows of [[0] * n] * m stay
one row, and a list in two dict values stays one list. A container a
written parameter shares with a parameter the call only reads is copied
back too.
A call that writes through none of its parameters, and takes no objects, reads its containers in place of copies. Its lists, inner lists included, are laid out in one block of memory the call owns rather than allocated one by one; a string in them is the Python string's own UTF-8 bytes, borrowed for the call, not a copy; a dict or a set is filled without hashing, and its index is made at the first lookup, so a walk over it never hashes. What the call hands back that it read (a row, a string) is the caller's object. The values are those the arguments held when the call began, as with a copy, so another thread may run while the call does. A string a cached callee keeps past the call is copied then.
What crosses costs time in proportion to its size. Measured on the generated wrapper:
| element | read in place | copied in, for a call that writes | and back, after a write |
|---|---|---|---|
| a number in a list | about 1 ns | about 1 ns | where it changed |
| a dict's or a set's entry | about 10 ns, and again at the first lookup | about 15 ns | about the same again |
| a list inside a list | about 20 ns, plus its elements | about 60 ns, plus its elements | its elements |
| a string | about 10 ns, borrowed | a native string, about 40 ns | a Python string |
Native code pays to read an element too: a string or an inner list is held
and let go of, a key is hashed and looked up. A Python loop's pass costs 10
to 30 ns. So Python calls a function natively only where the body does
enough with each element: a loop over a list of numbers or of bools; three
or more operations per entry of a dict it walks (s += k * v + v), more
where it looks keys up (s += d[k] stays in Python); a loop over each
inner list of a list of lists, or over each string's characters, rather
than one operation per row or per string. Otherwise Python calls its Python
body, and native callers still call it natively. ppy explain gives the
reason.
grow(xs, 3) from Python runs natively and leaves xs holding the three
squares after what it held.
Printing¶
Natively, under ppy run and in a standalone build, print(xs),
print(d), and an f-string field holding a list or a dict write what
repr writes: numbers, strings with their quotes, tuples, nested
containers, and dataclasses shown as Point(x=1, y=2.0). A set of ints or
of tuples of ints prints in CPython's order, and an empty one as set().
A list parameter lent as a buffer (a list of numbers the function only
reads) has no repr natively, so printing one keeps the function in
Python.
Limitations¶
- A tuple element holding a string or an object (
list[tuple[str, int]]) keeps the function in Python. - A dict or set keyed by
floatorboolis native, with0.0and-0.0one key. A NaN key, which only its own object finds, falls back. Anintkey given to a dict of floats (d[1]whered: dict[float, int]) stays in Python, since CPython keeps and prints the key as it came. d.get(k)with no default givesNonefor a missing key, for a dict of numbers, of numbers or strings that may beNone, of strings, and of objects of an object class (a value class's stays in Python). Bound to a local, passed to anint | Noneparameter, or returned from an-> int | Nonefunction, it keeps CPython's meaning (Numbers and strings that may beNone):v is None,if v:,print(v), andv or defaultare native, andvis read as a number once a test has shown it holds one. The checker reportsv += xon avthat may still beNoneasE1302, with or without strict mode. With a default,getis native for a dict whose values cannot beNone;d.get(k, 0)of adict[str, int | None]stays in Python.- Sorting,
min, andmaxover elements that may beNone, and keys that may beNone, stay in Python. r: list[int | None] = [None] * wis a checker error (E1301: the display is alist[NoneType]). Inside a comprehension assigned to an annotated name or field,[[None] * w for _ in range(h)]is accepted and lowers; returned directly, it keeps the function in Python.sort(key=...),sorted(key=...),min(key=...), andmax(key=...)natively take a key giving numbers or tuples of them, andminandmaxwith a key pick among numbers. Functions as values has the rest.anyandallof a generator are native and stop at the first answer, as CPython's do; of a list they are native too.- A standalone binary's
KeyErrorfor a string key saysKeyErrorwithout the key. - A container of objects or dataclasses crosses from Python as objects do. A container of objects whose class is an exception or generic keeps a Python caller on the Python body; native callers are not affected.
Examples: Collections, Strings.