Reference
Built-in functions
Edge Python provides 65 built-in functions. They are first-class values. You can pass them as arguments, store them in containers, and alias them.
[3, '-0x3', '-3'] aliased
Why is there no eval, exec or open?
Every module a program can reach is resolved and verified at compile time. The sandbox holds no file handles. eval, exec, compile, open and __import__ would break both rules, and none of them exists.
Output
print(*args, sep=' ', end='\n') writes the arguments joined by sep, then end.
*unpacking spreads an iterable into the arguments.- The
fileandflushkeywords are accepted and ignored.
1 2 3 a-b-c no newline! 1, 2, 3
input
input() pops one line from the input buffer of the host and returns it as a string.
- There is no prompt argument.
- The CLI fills the buffer from piped stdin, one line per call.
- In WASM the host copies stdin bytes into the guest input buffer before the run.
- An empty buffer raises
RuntimeError.
Numeric
abs
abs(x) returns the absolute value of an int or float. An instance whose class defines __abs__ returns what that method gives. Other types raise TypeError.
7 3.14
round
round(x) rounds to the nearest integer and returns an int.
- Ties go to even.
round(x, n)rounds tondecimal digits and returns a float.- A negative
nrounds to tens, hundreds, and so on.
2 0 -2 1.6 1200
min, max
min(a, b, ...) takes several values or a single iterable. max works the same way.
- An empty iterable raises
ValueErrorunlessdefault=is given. - A
key=function selects the comparison value. The original element is returned.
1 4 -1 bb
sum
sum(iterable) or sum(iterable, start). An empty iterable sums to start. It defaults to 0.
6 106 30
pow
pow(base, exp) matches the ** operator. pow(base, exp, mod) does modular exponentiation on integers.
- The exponent must be non-negative, else
ValueError. - The modulus must stay below 2^63 in absolute value, else
ValueError. - A zero modulus raises
ZeroDivisionError.
1024 24 7
divmod
divmod(a, b) returns (a // b, a % b) as a tuple. Ints and floats both work. Float operands give a float quotient and remainder.
(2, 1) (-3, 2) (3.0, 1.5)
bin, oct, hex
bin(x), oct(x), and hex(x) format an integer in base 2, 8, or 16 with the matching prefix.
0b1010 0o10 0xff -0x100
Type conversion
int
int(x) accepts an int, bool, float, or numeric string. An instance whose class defines __int__ returns what that method gives.
- Floats truncate toward zero.
- Strings accept
_as a digit separator. int(s, base)parses a string in radix 2 to 36. Radix 0 detects a0x,0o, or0bprefix.- A bad string raises
ValueError. int(inf)raisesOverflowErrorandint(nan)raisesValueError.- Results are bounded by the integer width.
3 42 1 255 31 1000
float
float(x) accepts an int, bool, float, or string. Strings recognize inf, -inf, and nan in any case. An instance whose class defines __float__ returns what that method gives.
2.0 3.14 inf
str
str(x) returns the display form of x. No argument gives an empty string. str(bytes, encoding) decodes bytes like bytes.decode.
42 [1, 2, 3] None hi
bool
bool(x) returns the truth value of x. The rules live in Truthy and falsy.
False True False True False True
bytes
bytes() builds an immutable byte sequence. It takes one of these forms.
| Call | Result |
|---|---|
bytes() | Empty bytes |
bytes(n) | n zero bytes. A negative n raises ValueError |
bytes(iterable) | One byte per int. A non-int raises TypeError and a value outside 0 to 255 raises ValueError |
bytes(b) | A copy of the bytes b |
bytes(s, encoding) | The string s encoded as "utf-8", "utf8" or "ascii" |
The encoding also passes as encoding=. A string without an encoding raises TypeError. ASCII raises UnicodeEncodeError on a non-ASCII character, and any other encoding name raises ValueError.
b'' b'\x00\x00\x00' b'Hi' b'\x00\x01\x02' b'h\xc3\xa9'
list, tuple, set, frozenset
Each accepts any iterable and builds a new container. Iterating a dict yields its keys. With no argument, each builds an empty container.
['a', 'b', 'c']
(0, 1, 2)
{'b', 'a'}
frozenset({3, 2, 1})dict
dict() builds from a mapping, an iterable of key and value pairs, keyword arguments, or a mix. Each pair must have length 2.
{'a': 1, 'b': 2}
{'a': 1}
{'a': 1, 'b': 2}chr, ord
chr(i) returns the one-character string for code point i, across full Unicode. Out-of-range values raise ValueError. ord(c) is the inverse and accepts a length-1 string or length-1 bytes.
A 65 65 😀
Sequences and iteration
len
len(x) returns the element count of a string in code points, or of bytes, a list, tuple, dict, set, frozenset or range.
An instance whose class defines __len__ returns what that method gives. The result must be a non-negative int. Other types raise TypeError.
5 4 2 100
range
range(stop), range(start, stop), or range(start, stop, step) builds a lazy range.
- Indexing and slicing compute without materialising.
range(10)[2:8:2]isrange(2, 8, 2). - A zero step raises
ValueError. - Non-integer arguments raise
TypeError. - Two ranges compare equal when they produce the same sequence of values.
[0, 1, 2, 3, 4] [2, 3, 4, 5, 6, 7] [10, 8, 6, 4, 2] True
sorted
sorted(iterable) returns a new sorted list. list.sort follows the same rules in place.
key=fncompares byfn(item).reverse=Trueflips the order.- Numbers, strings, bytes, and lists or tuples order lexicographically.
- Objects with
__lt__sort by it. - Mixing unordered types raises
TypeError.
[1, 1, 3, 4, 5] ['e', 'h', 'l', 'l', 'o'] [5, 4, 3, 1, 1] ['kiwi', 'apple', 'banana']
reversed
reversed(x) returns an iterator over a sequence, a dict or a dict view, from its last item. Over a list it reads the list as it goes. A set is not reversible and raises TypeError.
[3, 2, 1] cba
enumerate
enumerate(iterable) returns an iterator of (index, value) tuples. A second argument, positional or start=, sets the first index.
0 a 1 b 2 c [(7, 'a'), (8, 'b')]
zip
zip(a, b, ...) returns an iterator of tuples pairing the inputs, truncated to the shortest. There is no strict= mode.
1 x 2 y [(1, 3, 5), (2, 4, 6)]
iter, next
iter(x) returns an iterator over any iterable.
- Over a list it reads the list as it goes.
- Over a
rangeit computes each step. - Over anything else it takes the items up front.
iter(callable, sentinel)callscallable()until it returnssentinel.
next(it) returns the next item in constant time and raises StopIteration when the iterator is exhausted. next(it, default) returns default instead of raising.
10 20 30 done
map, filter
map(fn, *iterables) returns an iterator over fn(items...). filter(pred, iterable) returns an iterator over the items where pred(item) is truthy.
mapwalks several iterables in parallel and stops at the shortest.- A
Nonepredicate keeps the truthy items. - Both call the function as each item is taken.
[2, 4, 6] [11, 22] [3, 4] [1, 'hi', [1]]
all, any
all(x) and any(x) test truthiness across an iterable and stop at the deciding element. all([]) is True and any([]) is False.
True False True True False
slice
slice(stop), slice(start, stop), or slice(start, stop, step) builds a reusable slice object that indexes a sequence. It exposes start, stop and step. s.indices(n) returns the bounds clamped to a sequence of length n.
[20, 30, 40] [10, 30, 50]
Bytes helpers
These three functions are the function forms of bytes and int methods. They take every argument by position and behave like the methods.
bytes_fromhex
bytes_fromhex(s) is bytes.fromhex(s). It parses a hex string into bytes and ignores ASCII whitespace. A non-hex character or an odd digit count raises ValueError.
int_from_bytes
int_from_bytes(b, order) is int.from_bytes(b, order) with the order required. It reads b as an unsigned integer. order is "big" or "little".
int_to_bytes
int_to_bytes(n, length, order) is n.to_bytes(length, order) with every argument required. It writes a non-negative int as length bytes. A negative n or a value that does not fit raises OverflowError.
b'Hello' 256 b'\x00\xff'
Types
type
type(x) returns the type object of x. The built-in type names are these same objects.
type(x) == int holds, and calling one constructs a value. For a user instance the result is its class object.
<class 'int'> True [4, 5] True
Functions, type objects, and classes expose __name__, the bare declared name. On an exception instance, type(e).__name__ gives the name of the exception class.
greet int ZeroDivisionError
object
object() returns a unique featureless instance. Use it as a sentinel. Every value is an instance of object.
False True True
isinstance
isinstance(obj, t) tests membership. t is a built-in type, exception class, user class, or a tuple of those.
boolcounts asint.- Exception classes follow the exception hierarchy.
- User classes walk their inheritance chain.
objectmatches every value.
True True True
issubclass
issubclass(C, B) tests inheritance. B may be a tuple of classes. C must be a class or the call raises TypeError.
bool is a subclass of int, and exception classes follow the same hierarchy.
True True True False
callable
callable(x) is True for functions, lambdas, bound methods, type objects, built-in functions, and instances whose class defines __call__. It is False for everything else.
True True False
Representation
repr
repr(x) returns the developer-readable form. Strings are quoted and containers show the repr of their elements.
'hello' 42 [1, 'two', 3]
format
format(value) returns the display form. format(value, spec) applies the format spec mini-language from f-strings.
42 00042 3.14 0xff
Attributes
getattr, hasattr
getattr(obj, name) reads an attribute. It looks in this order.
- The instance
__dict__. - The class chain.
- The built-in method table.
- The
__getattr__of the class, when it defines one.
A missing name raises AttributeError unless a third argument gives a default. hasattr(obj, name) runs the same lookup and returns a boolean.
setattr, delattr
setattr(obj, name, value) writes an attribute on a user instance, class, or function. Built-in types have no writable attributes.
delattr(obj, name) removes an attribute. A missing name raises AttributeError.
42 default False
vars
vars(x) returns a snapshot of the attribute dict of an instance or module. There is no form without an argument.
{'x': 1, 'y': 2}globals
globals() returns a fresh dict of the module-level bindings. It holds user names only. Built-ins live in a separate namespace.
It is a copy. Mutating it does not change any binding.
100 7
Modules
import_module
import_module(name) returns a module that the program imports statically somewhere. It is a lookup, not a load.
- Every reachable module is still resolved and verified at compile time.
- An unknown name raises
NameError. - A name bound to a global that is not a module, such as a function, raises
TypeError.
True 3
Dynamic loading through importlib or __import__ does not exist. Static imports plus import_module replace it.
Classes
These builtins shape class members. Classes owns their behavior and examples.
super()takes no arguments and works inside a method only. It resolves attributes against the bases of the current class. See Inheritance and super().property(fget, fset=None)builds a property for a class member, usually through@propertyand@<name>.setter. See Properties.staticmethod(func)wraps a member so it receives no implicitself. See Static methods.classmethod(func)wraps a member so it receives the class as its first argument. See Class methods.
Async
These builtins drive coroutines and messages. Async owns the model and the examples.
run(*coros)runs every argument to completion and returns the result of the first. Errors from the other coroutines are discarded.gather(*coros)runs every argument and returns a list of results in argument order. It waits for every coroutine, then raises the error of the first failing one in argument order.sleep(seconds)suspends for the duration. A negative value counts as zero.with_timeout(seconds, coro)returns the result of the coroutine or raisesTimeoutErrorat the deadline.cancel(coro)flags a coroutine for cancellation at its next step. Itsfinallyblocks run, and it cannot catch theCancelledError.receive()pops the oldest message the host queued. It parks the coroutine while the queue is empty.send(group, body)hands the stringbodyto an actor ofgroupand returnsNone. Outside an actor pool it raisesRuntimeError.