// PYTHONRS — BUILTIN REFERENCE

pythonrs v0.1.0 · Python on fusevm · lex/parse → AST → bytecode → Cranelift JIT · transparent rkyv cache on every run · AOT native-exe via --build · MIT · in active development

Docs GitHub
// Color scheme

>_BUILTIN REFERENCE

Every reserved keyword, builtin function, and core type method the current pythonrs build recognizes, grouped by keyword set then builtin then type. This page is generated from the language-server corpus (src/lsp.rs) by the gen-docs binary, so it stays in sync with what the runtime and editor tooling actually know about. Keywords mirror lexer.rs; each builtin and method mirrors a real dispatch arm in src/builtins.rs.

Keyword

# def

define a function; the body runs on call and returns via `return` (else None)

def greet(): return "hi"
greet()   # => 'hi'

# class

define a class; the body populates its namespace and base list

class A: pass
A().__class__.__name__   # => 'A'

# return

return a value from the current function (None if omitted)

def f(): return 9
f()   # => 9

# lambda

anonymous single-expression function: `lambda args: expr`

(lambda x: x * 2)(4)   # => 8

# yield

suspend a generator, yielding a value to the caller

def g():
    yield 1
list(g())   # => [1]

# import

import a module by name into the current namespace

import math
math.sqrt(16)   # => 4.0

# from

import specific names from a module: `from m import a, b`

from math import sqrt
sqrt(9)   # => 3.0

# as

bind an import / with / except target to a name

import math as m
m.floor(3.7)   # => 3

# if

conditional branch; also the `x if cond else y` expression

x = 5 if True else 0
x   # => 5

# elif

additional condition branch inside an if

if False: pass
elif True: x = 2   # x => 2

# else

fallback branch of an if / for / while / try

if False: x = 1
else: x = 2   # x => 2

# while

loop while the condition is truthy

i = 0
while i < 3: i += 1
i   # => 3

# for

iterate over an iterable: `for x in iterable:`

s = 0
for n in [1, 2, 3]: s += n
s   # => 6

# in

membership test, and the `for x in …` separator

3 in [1, 2, 3]   # => True

# is

identity test (same object), not value equality

a = None
a is None   # => True

# not

logical negation (also `not in` / `is not`)

not False   # => True

# and

short-circuiting logical AND; returns an operand

1 and 2   # => 2

# or

short-circuiting logical OR; returns an operand

None or 5   # => 5

# try

open an exception-handling block (except/else/finally)

try:
    1 / 0
except ZeroDivisionError:
    x = -1   # x => -1

# except

handle a raised exception, optionally by class and `as` name

try: raise ValueError("e")
except ValueError as e: str(e)   # => 'e'

# finally

block that always runs whether or not an exception was raised

try: x = 1
finally: y = 2   # y => 2

# raise

raise an exception (bare re-raises the active one)

raise ValueError("boom")   # raises ValueError: boom

# with

context-manager block: `with ctx as name:` (enter/exit)

with open("f") as fh: data = fh.read()

# pass

no-op statement placeholder

def stub(): pass   # defines a no-op function

# break

exit the nearest enclosing loop immediately

for n in [1, 2, 3]:
    if n == 2: break   # stops at 2

# continue

skip to the next iteration of the nearest loop

for n in [1, 2, 3]:
    if n == 2: continue   # skips 2

# del

delete a name, item, or attribute binding

d = {'a': 1}
del d['a']
d   # => {}

# assert

raise AssertionError if the condition is falsey

assert 1 + 1 == 2   # passes silently

# global

declare that a name refers to the module-global binding

x = 0
def f():
    global x
    x = 5

# nonlocal

bind a name to the nearest enclosing function scope

def outer():
    x = 0
    def inner():
        nonlocal x
        x = 5

# async

define a coroutine (`async def`) or async loop/with

async def fetch(): return 1

# await

suspend a coroutine until the awaitable resolves

async def f(): return await g()

# match

structural pattern-match statement (`match subject:`)

match [1, 2]:
    case [a, b]: a + b   # => 3

# case

a match branch; binds/tests against a pattern

match 2:
    case 1: x = 'a'
    case _: x = 'b'   # x => 'b'

# None

the sole NoneType instance; the null / absent value

(None is None)   # => True

# True

the boolean true value (an int subtype equal to 1)

True + 1   # => 2

# False

the boolean false value (an int subtype equal to 0)

False or 7   # => 7

Builtin

# print

write args to stdout, space-separated, ending in newline

print("hi")   # prints hi, returns None

# len

number of items in a container (str/list/tuple/dict/set)

len([1, 2, 3])   # => 3

# range

arithmetic progression: range(stop) or range(start, stop[, step])

list(range(3))   # => [0, 1, 2]

# int

convert to an arbitrary-precision integer (optional base)

int("ff", 16)   # => 255

# float

convert a number or string to a floating-point value

float("3.5")   # => 3.5

# str

string form of an object (like calling __str__)

str(123)   # => '123'

# repr

canonical string representation of an object

repr("hi")   # => "'hi'"

# bool

truth value of x as True or False

bool([])   # => False

# list

build a list, optionally from an iterable

list("ab")   # => ['a', 'b']

# tuple

build an immutable tuple, optionally from an iterable

tuple([1, 2])   # => (1, 2)

# dict

build a dict from kwargs / pairs / mapping

dict(a=1)   # => {'a': 1}

# set

build a set (unique members) from an iterable

set([1, 1, 2])   # => {1, 2}

# frozenset

build an immutable, hashable set from an iterable

frozenset([1, 2])   # => frozenset({1, 2})

# bytes

immutable bytes object from a string/iterable/size

bytes("AB", "utf-8")   # => b'AB'

# sum

sum of an iterable, plus an optional start value

sum([1, 2, 3])   # => 6

# min

smallest item of an iterable or of the args

min([3, 1, 2])   # => 1

# max

largest item of an iterable or of the args

max(3, 1, 2)   # => 3

# sorted

a new sorted list (optional key= and reverse=)

sorted([3, 1, 2])   # => [1, 2, 3]

# reversed

an iterator over a sequence in reverse order

list(reversed([1, 2, 3]))   # => [3, 2, 1]

# enumerate

iterator of (index, value) pairs (optional start=)

list(enumerate("ab"))   # => [(0, 'a'), (1, 'b')]

# zip

iterator of tuples pairing items from each iterable

list(zip([1, 2], [3, 4]))   # => [(1, 3), (2, 4)]

# map

apply a function across one or more iterables (lazy)

list(map(str, [1, 2]))   # => ['1', '2']

# filter

items of an iterable where func is truthy (lazy)

list(filter(None, [0, 1, 2]))   # => [1, 2]

# any

True if any item of the iterable is truthy

any([0, 0, 1])   # => True

# all

True if every item of the iterable is truthy

all([1, 2, 3])   # => True

# abs

absolute value / magnitude of a number

abs(-5)   # => 5

# round

round a number to optional ndigits (banker's rounding)

round(3.14159, 2)   # => 3.14

# divmod

return the pair (a // b, a % b)

divmod(7, 2)   # => (3, 1)

# pow

x ** y, or pow(x, y, mod) for modular exponentiation

pow(2, 10)   # => 1024

# type

the type/class of an object

type(3).__name__   # => 'int'

# isinstance

True if the object is an instance of the class(es)

isinstance(3, int)   # => True

# issubclass

True if the first class is a subclass of the second

issubclass(bool, int)   # => True

# callable

True if the object can be called like a function

callable(len)   # => True

# hasattr

True if the object has the named attribute

hasattr("hi", "upper")   # => True

# getattr

read an attribute by name (optional default)

getattr("hi", "upper")()   # => 'HI'

# setattr

set an attribute by name on an object

setattr(obj, "x", 7)   # obj.x => 7

# vars

the object's __dict__ (namespace mapping)

vars(obj)   # => {...}

# dir

sorted list of an object's attribute names

dir(obj)   # => [...]

# id

the identity (address) integer of an object

id(obj)   # => a stable int

# hash

the hash value of a hashable object

hash((1, 2))   # => an int

# iter

return an iterator over the argument

next(iter([9, 8]))   # => 9

# next

advance an iterator (optional default on exhaustion)

next(iter([9]))   # => 9

# input

read a line from stdin (optional prompt), no newline

input("name: ")   # reads one line

# ord

Unicode code point of a one-character string

ord("A")   # => 65

# chr

one-character string for a Unicode code point

chr(65)   # => 'A'

# hex

'0x'-prefixed hexadecimal string of an integer

hex(255)   # => '0xff'

# oct

'0o'-prefixed octal string of an integer

oct(8)   # => '0o10'

# bin

'0b'-prefixed binary string of an integer

bin(5)   # => '0b101'

# ascii

repr of an object with non-ASCII chars escaped

ascii("é")   # => "'\\xe9'"

# complex

build a complex number from real and imaginary parts

complex(1, 2)   # => (1+2j)

# format

format a value using a format spec string

format(255, "x")   # => 'ff'

# object

the base object; object() is a featureless instance

object().__class__.__name__   # => 'object'

# nan

the IEEE 754 not-a-number float value

nan != nan   # => True

math

# sqrt

square root as a float

math.sqrt(16)   # => 4.0

# pow

x raised to the power y, as a float

math.pow(2, 3)   # => 8.0

# floor

largest integer <= x

math.floor(3.7)   # => 3

# ceil

smallest integer >= x

math.ceil(3.2)   # => 4

# fabs

absolute value as a float

math.fabs(-5)   # => 5.0

# factorial

n! for a non-negative integer n

math.factorial(5)   # => 120

# gcd

greatest common divisor of the integer args

math.gcd(12, 8)   # => 4

# log

natural log, or log base b when a second arg is given

math.log(8, 2)   # => 3.0

# sin

sine of x (radians)

math.sin(0)   # => 0.0

# cos

cosine of x (radians)

math.cos(0)   # => 1.0

str

# upper

copy with all cased characters uppercased

"abc".upper()   # => 'ABC'

# lower

copy with all cased characters lowercased

"ABC".lower()   # => 'abc'

# casefold

aggressive lowercase for caseless matching

"ABC".casefold()   # => 'abc'

# strip

copy with leading and trailing chars (default whitespace) removed

"  hi  ".strip()   # => 'hi'

# lstrip

copy with leading chars (default whitespace) removed

"  hi".lstrip()   # => 'hi'

# rstrip

copy with trailing chars (default whitespace) removed

"hi  ".rstrip()   # => 'hi'

# swapcase

copy with the case of every letter inverted

"Abc".swapcase()   # => 'aBC'

# capitalize

copy with the first char upper, the rest lower

"hELLO".capitalize()   # => 'Hello'

# title

copy with the first letter of each word uppercased

"a b".title()   # => 'A B'

# split

list of substrings split on sep (default: runs of whitespace)

"a,b,c".split(",")   # => ['a', 'b', 'c']

# rsplit

like split, but scanning from the right (honours maxsplit)

"a,b,c".rsplit(",", 1)   # => ['a,b', 'c']

# splitlines

list of lines, splitting at line boundaries

"a\nb".splitlines()   # => ['a', 'b']

# join

concatenate an iterable of strings using self as separator

",".join(["a", "b"])   # => 'a,b'

# replace

copy with occurrences of old replaced by new (optional count)

"aaa".replace("a", "b", 2)   # => 'bba'

# startswith

True if the string starts with the given prefix

"hello".startswith("he")   # => True

# endswith

True if the string ends with the given suffix

"hello".endswith("lo")   # => True

# find

lowest index of substring, or -1 if not found

"hello".find("l")   # => 2

# rfind

highest index of substring, or -1 if not found

"hello".rfind("l")   # => 3

# index

like find, but raises ValueError if the substring is absent

"hello".index("e")   # => 1

# count

number of non-overlapping occurrences of the substring

"hello".count("l")   # => 2

# isdigit

True if non-empty and every char is a digit

"123".isdigit()   # => True

# isalpha

True if non-empty and every char is alphabetic

"abc".isalpha()   # => True

# isalnum

True if non-empty and every char is alphanumeric

"a1".isalnum()   # => True

# isspace

True if non-empty and every char is whitespace

"  ".isspace()   # => True

# isupper

True if it has cased chars and they are all uppercase

"ABC".isupper()   # => True

# islower

True if it has cased chars and they are all lowercase

"abc".islower()   # => True

# zfill

right-justify to width, padding with '0' (respects sign)

"42".zfill(5)   # => '00042'

# center

center in a field of width, padding with fillchar (default space)

"hi".center(6)   # => '  hi  '

# ljust

left-justify in a field of width, padding on the right

"hi".ljust(5)   # => 'hi   '

# rjust

right-justify in a field of width, padding on the left

"hi".rjust(5)   # => '   hi'

# removeprefix

copy with the prefix removed if present, else unchanged

"unhappy".removeprefix("un")   # => 'happy'

# removesuffix

copy with the suffix removed if present, else unchanged

"file.py".removesuffix(".py")   # => 'file'

# encode

encode the string to a bytes object (default UTF-8)

"ab".encode()   # => b'ab'

# format

substitute {} / {name} fields with the given args

"{}-{}".format(1, 2)   # => '1-2'

list

# append

add a single item to the end of the list (in place)

x = [1]; x.append(2); x   # => [1, 2]

# extend

append every item from an iterable (in place)

x = [1]; x.extend([2, 3]); x   # => [1, 2, 3]

# insert

insert an item before the given index (in place)

x = [1, 3]; x.insert(1, 2); x   # => [1, 2, 3]

# pop

remove and return item at index (default last)

x = [1, 2, 3]; x.pop()   # => 3

# remove

remove the first item equal to the value (in place)

x = [1, 2, 2]; x.remove(2); x   # => [1, 2]

# clear

remove all items from the list (in place)

x = [1, 2]; x.clear(); x   # => []

# index

index of the first item equal to the value (ValueError if none)

[1, 2, 3].index(2)   # => 1

# count

number of items equal to the value

[1, 1, 2].count(1)   # => 2

# reverse

reverse the list in place

x = [1, 2, 3]; x.reverse(); x   # => [3, 2, 1]

# copy

a shallow copy of the list

[1, 2].copy()   # => [1, 2]

# sort

sort the list in place (optional key= and reverse=)

x = [3, 1, 2]; x.sort(); x   # => [1, 2, 3]

dict

# keys

a view of the dictionary's keys

list({'a': 1}.keys())   # => ['a']

# values

a view of the dictionary's values

list({'a': 1}.values())   # => [1]

# items

a view of the dictionary's (key, value) pairs

list({'a': 1}.items())   # => [('a', 1)]

# get

value for key, or a default (None) if the key is absent

{'a': 1}.get("b", 0)   # => 0

# pop

remove key and return its value (or a supplied default)

{'a': 1}.pop("a")   # => 1

# setdefault

value for key; insert it with a default if absent

d = {}; d.setdefault("a", 1)   # => 1

# update

merge another mapping / pairs into this dict (in place)

d = {'a': 1}; d.update({'b': 2}); d   # => {'a': 1, 'b': 2}

# popitem

remove and return the last-inserted (key, value) pair

{'a': 1}.popitem()   # => ('a', 1)

set

# add

add an element to the set (in place; a no-op if present)

s = {1}; s.add(2); s   # => {1, 2}

# discard

remove an element if present; no error if it is absent

s = {1, 2}; s.discard(3); s   # => {1, 2}

# union

a new set with elements from this set and the others

{1}.union({2})   # => {1, 2}

# intersection

a new set with elements common to all the sets

{1, 2}.intersection({2, 3})   # => {2}

# difference

a new set with elements in this set but not the others

{1, 2}.difference({2})   # => {1}

# symmetric_difference

a new set with elements in exactly one of the two sets

{1, 2}.symmetric_difference({2, 3})   # => {1, 3}

# issubset

True if every element of this set is in the other

{1}.issubset({1, 2})   # => True

# issuperset

True if this set contains every element of the other

{1, 2}.issuperset({1})   # => True

tuple

# count

number of items equal to the value

(1, 1, 2).count(1)   # => 2

# index

index of the first item equal to the value

(1, 2, 3).index(2)   # => 1

int

# bit_length

number of bits needed to represent abs(self) in binary

255 .bit_length()   # => 8

# conjugate

the complex conjugate; for a real number, self

(5).conjugate()   # => 5

float

# is_integer

True if the float has no fractional part

(3.0).is_integer()   # => True

More