# def
define a function; the body runs on call and returns via `return` (else None)
def greet(): return "hi"
greet() # => 'hi'
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
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.
defdefine a function; the body runs on call and returns via `return` (else None)
def greet(): return "hi"
greet() # => 'hi'
classdefine a class; the body populates its namespace and base list
class A: pass
A().__class__.__name__ # => 'A'
returnreturn a value from the current function (None if omitted)
def f(): return 9
f() # => 9
lambdaanonymous single-expression function: `lambda args: expr`
(lambda x: x * 2)(4) # => 8
yieldsuspend a generator, yielding a value to the caller
def g():
yield 1
list(g()) # => [1]
importimport a module by name into the current namespace
import math
math.sqrt(16) # => 4.0
fromimport specific names from a module: `from m import a, b`
from math import sqrt
sqrt(9) # => 3.0
asbind an import / with / except target to a name
import math as m
m.floor(3.7) # => 3
ifconditional branch; also the `x if cond else y` expression
x = 5 if True else 0
x # => 5
elifadditional condition branch inside an if
if False: pass
elif True: x = 2 # x => 2
elsefallback branch of an if / for / while / try
if False: x = 1
else: x = 2 # x => 2
whileloop while the condition is truthy
i = 0
while i < 3: i += 1
i # => 3
foriterate over an iterable: `for x in iterable:`
s = 0
for n in [1, 2, 3]: s += n
s # => 6
inmembership test, and the `for x in …` separator
3 in [1, 2, 3] # => True
isidentity test (same object), not value equality
a = None
a is None # => True
notlogical negation (also `not in` / `is not`)
not False # => True
andshort-circuiting logical AND; returns an operand
1 and 2 # => 2
orshort-circuiting logical OR; returns an operand
None or 5 # => 5
tryopen an exception-handling block (except/else/finally)
try:
1 / 0
except ZeroDivisionError:
x = -1 # x => -1
excepthandle a raised exception, optionally by class and `as` name
try: raise ValueError("e")
except ValueError as e: str(e) # => 'e'
finallyblock that always runs whether or not an exception was raised
try: x = 1
finally: y = 2 # y => 2
raiseraise an exception (bare re-raises the active one)
raise ValueError("boom") # raises ValueError: boom
withcontext-manager block: `with ctx as name:` (enter/exit)
with open("f") as fh: data = fh.read()
passno-op statement placeholder
def stub(): pass # defines a no-op function
breakexit the nearest enclosing loop immediately
for n in [1, 2, 3]:
if n == 2: break # stops at 2
continueskip to the next iteration of the nearest loop
for n in [1, 2, 3]:
if n == 2: continue # skips 2
deldelete a name, item, or attribute binding
d = {'a': 1}
del d['a']
d # => {}
assertraise AssertionError if the condition is falsey
assert 1 + 1 == 2 # passes silently
globaldeclare that a name refers to the module-global binding
x = 0
def f():
global x
x = 5
nonlocalbind a name to the nearest enclosing function scope
def outer():
x = 0
def inner():
nonlocal x
x = 5
asyncdefine a coroutine (`async def`) or async loop/with
async def fetch(): return 1
awaitsuspend a coroutine until the awaitable resolves
async def f(): return await g()
matchstructural pattern-match statement (`match subject:`)
match [1, 2]:
case [a, b]: a + b # => 3
casea match branch; binds/tests against a pattern
match 2:
case 1: x = 'a'
case _: x = 'b' # x => 'b'
Nonethe sole NoneType instance; the null / absent value
(None is None) # => True
Truethe boolean true value (an int subtype equal to 1)
True + 1 # => 2
Falsethe boolean false value (an int subtype equal to 0)
False or 7 # => 7
printwrite args to stdout, space-separated, ending in newline
print("hi") # prints hi, returns None
lennumber of items in a container (str/list/tuple/dict/set)
len([1, 2, 3]) # => 3
rangearithmetic progression: range(stop) or range(start, stop[, step])
list(range(3)) # => [0, 1, 2]
intconvert to an arbitrary-precision integer (optional base)
int("ff", 16) # => 255
floatconvert a number or string to a floating-point value
float("3.5") # => 3.5
strstring form of an object (like calling __str__)
str(123) # => '123'
reprcanonical string representation of an object
repr("hi") # => "'hi'"
booltruth value of x as True or False
bool([]) # => False
listbuild a list, optionally from an iterable
list("ab") # => ['a', 'b']
tuplebuild an immutable tuple, optionally from an iterable
tuple([1, 2]) # => (1, 2)
dictbuild a dict from kwargs / pairs / mapping
dict(a=1) # => {'a': 1}
setbuild a set (unique members) from an iterable
set([1, 1, 2]) # => {1, 2}
frozensetbuild an immutable, hashable set from an iterable
frozenset([1, 2]) # => frozenset({1, 2})
bytesimmutable bytes object from a string/iterable/size
bytes("AB", "utf-8") # => b'AB'
sumsum of an iterable, plus an optional start value
sum([1, 2, 3]) # => 6
minsmallest item of an iterable or of the args
min([3, 1, 2]) # => 1
maxlargest item of an iterable or of the args
max(3, 1, 2) # => 3
sorteda new sorted list (optional key= and reverse=)
sorted([3, 1, 2]) # => [1, 2, 3]
reversedan iterator over a sequence in reverse order
list(reversed([1, 2, 3])) # => [3, 2, 1]
enumerateiterator of (index, value) pairs (optional start=)
list(enumerate("ab")) # => [(0, 'a'), (1, 'b')]
zipiterator of tuples pairing items from each iterable
list(zip([1, 2], [3, 4])) # => [(1, 3), (2, 4)]
mapapply a function across one or more iterables (lazy)
list(map(str, [1, 2])) # => ['1', '2']
filteritems of an iterable where func is truthy (lazy)
list(filter(None, [0, 1, 2])) # => [1, 2]
anyTrue if any item of the iterable is truthy
any([0, 0, 1]) # => True
allTrue if every item of the iterable is truthy
all([1, 2, 3]) # => True
absabsolute value / magnitude of a number
abs(-5) # => 5
roundround a number to optional ndigits (banker's rounding)
round(3.14159, 2) # => 3.14
divmodreturn the pair (a // b, a % b)
divmod(7, 2) # => (3, 1)
powx ** y, or pow(x, y, mod) for modular exponentiation
pow(2, 10) # => 1024
typethe type/class of an object
type(3).__name__ # => 'int'
isinstanceTrue if the object is an instance of the class(es)
isinstance(3, int) # => True
issubclassTrue if the first class is a subclass of the second
issubclass(bool, int) # => True
callableTrue if the object can be called like a function
callable(len) # => True
hasattrTrue if the object has the named attribute
hasattr("hi", "upper") # => True
getattrread an attribute by name (optional default)
getattr("hi", "upper")() # => 'HI'
setattrset an attribute by name on an object
setattr(obj, "x", 7) # obj.x => 7
varsthe object's __dict__ (namespace mapping)
vars(obj) # => {...}
dirsorted list of an object's attribute names
dir(obj) # => [...]
idthe identity (address) integer of an object
id(obj) # => a stable int
hashthe hash value of a hashable object
hash((1, 2)) # => an int
iterreturn an iterator over the argument
next(iter([9, 8])) # => 9
nextadvance an iterator (optional default on exhaustion)
next(iter([9])) # => 9
inputread a line from stdin (optional prompt), no newline
input("name: ") # reads one line
ordUnicode code point of a one-character string
ord("A") # => 65
chrone-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'
asciirepr of an object with non-ASCII chars escaped
ascii("é") # => "'\\xe9'"
complexbuild a complex number from real and imaginary parts
complex(1, 2) # => (1+2j)
formatformat a value using a format spec string
format(255, "x") # => 'ff'
objectthe base object; object() is a featureless instance
object().__class__.__name__ # => 'object'
nanthe IEEE 754 not-a-number float value
nan != nan # => True
sqrtsquare root as a float
math.sqrt(16) # => 4.0
powx raised to the power y, as a float
math.pow(2, 3) # => 8.0
floorlargest integer <= x
math.floor(3.7) # => 3
ceilsmallest integer >= x
math.ceil(3.2) # => 4
fabsabsolute value as a float
math.fabs(-5) # => 5.0
factorialn! for a non-negative integer n
math.factorial(5) # => 120
gcdgreatest common divisor of the integer args
math.gcd(12, 8) # => 4
lognatural log, or log base b when a second arg is given
math.log(8, 2) # => 3.0
sinsine of x (radians)
math.sin(0) # => 0.0
coscosine of x (radians)
math.cos(0) # => 1.0
uppercopy with all cased characters uppercased
"abc".upper() # => 'ABC'
lowercopy with all cased characters lowercased
"ABC".lower() # => 'abc'
casefoldaggressive lowercase for caseless matching
"ABC".casefold() # => 'abc'
stripcopy with leading and trailing chars (default whitespace) removed
" hi ".strip() # => 'hi'
lstripcopy with leading chars (default whitespace) removed
" hi".lstrip() # => 'hi'
rstripcopy with trailing chars (default whitespace) removed
"hi ".rstrip() # => 'hi'
swapcasecopy with the case of every letter inverted
"Abc".swapcase() # => 'aBC'
capitalizecopy with the first char upper, the rest lower
"hELLO".capitalize() # => 'Hello'
titlecopy with the first letter of each word uppercased
"a b".title() # => 'A B'
splitlist of substrings split on sep (default: runs of whitespace)
"a,b,c".split(",") # => ['a', 'b', 'c']
rsplitlike split, but scanning from the right (honours maxsplit)
"a,b,c".rsplit(",", 1) # => ['a,b', 'c']
splitlineslist of lines, splitting at line boundaries
"a\nb".splitlines() # => ['a', 'b']
joinconcatenate an iterable of strings using self as separator
",".join(["a", "b"]) # => 'a,b'
replacecopy with occurrences of old replaced by new (optional count)
"aaa".replace("a", "b", 2) # => 'bba'
startswithTrue if the string starts with the given prefix
"hello".startswith("he") # => True
endswithTrue if the string ends with the given suffix
"hello".endswith("lo") # => True
findlowest index of substring, or -1 if not found
"hello".find("l") # => 2
rfindhighest index of substring, or -1 if not found
"hello".rfind("l") # => 3
indexlike find, but raises ValueError if the substring is absent
"hello".index("e") # => 1
countnumber of non-overlapping occurrences of the substring
"hello".count("l") # => 2
isdigitTrue if non-empty and every char is a digit
"123".isdigit() # => True
isalphaTrue if non-empty and every char is alphabetic
"abc".isalpha() # => True
isalnumTrue if non-empty and every char is alphanumeric
"a1".isalnum() # => True
isspaceTrue if non-empty and every char is whitespace
" ".isspace() # => True
isupperTrue if it has cased chars and they are all uppercase
"ABC".isupper() # => True
islowerTrue if it has cased chars and they are all lowercase
"abc".islower() # => True
zfillright-justify to width, padding with '0' (respects sign)
"42".zfill(5) # => '00042'
centercenter in a field of width, padding with fillchar (default space)
"hi".center(6) # => ' hi '
ljustleft-justify in a field of width, padding on the right
"hi".ljust(5) # => 'hi '
rjustright-justify in a field of width, padding on the left
"hi".rjust(5) # => ' hi'
removeprefixcopy with the prefix removed if present, else unchanged
"unhappy".removeprefix("un") # => 'happy'
removesuffixcopy with the suffix removed if present, else unchanged
"file.py".removesuffix(".py") # => 'file'
encodeencode the string to a bytes object (default UTF-8)
"ab".encode() # => b'ab'
formatsubstitute {} / {name} fields with the given args
"{}-{}".format(1, 2) # => '1-2'
appendadd a single item to the end of the list (in place)
x = [1]; x.append(2); x # => [1, 2]
extendappend every item from an iterable (in place)
x = [1]; x.extend([2, 3]); x # => [1, 2, 3]
insertinsert an item before the given index (in place)
x = [1, 3]; x.insert(1, 2); x # => [1, 2, 3]
popremove and return item at index (default last)
x = [1, 2, 3]; x.pop() # => 3
removeremove the first item equal to the value (in place)
x = [1, 2, 2]; x.remove(2); x # => [1, 2]
clearremove all items from the list (in place)
x = [1, 2]; x.clear(); x # => []
indexindex of the first item equal to the value (ValueError if none)
[1, 2, 3].index(2) # => 1
countnumber of items equal to the value
[1, 1, 2].count(1) # => 2
reversereverse the list in place
x = [1, 2, 3]; x.reverse(); x # => [3, 2, 1]
copya shallow copy of the list
[1, 2].copy() # => [1, 2]
sortsort the list in place (optional key= and reverse=)
x = [3, 1, 2]; x.sort(); x # => [1, 2, 3]
keysa view of the dictionary's keys
list({'a': 1}.keys()) # => ['a']
valuesa view of the dictionary's values
list({'a': 1}.values()) # => [1]
itemsa view of the dictionary's (key, value) pairs
list({'a': 1}.items()) # => [('a', 1)]
getvalue for key, or a default (None) if the key is absent
{'a': 1}.get("b", 0) # => 0
popremove key and return its value (or a supplied default)
{'a': 1}.pop("a") # => 1
setdefaultvalue for key; insert it with a default if absent
d = {}; d.setdefault("a", 1) # => 1
updatemerge another mapping / pairs into this dict (in place)
d = {'a': 1}; d.update({'b': 2}); d # => {'a': 1, 'b': 2}
popitemremove and return the last-inserted (key, value) pair
{'a': 1}.popitem() # => ('a', 1)
addadd an element to the set (in place; a no-op if present)
s = {1}; s.add(2); s # => {1, 2}
discardremove an element if present; no error if it is absent
s = {1, 2}; s.discard(3); s # => {1, 2}
uniona new set with elements from this set and the others
{1}.union({2}) # => {1, 2}
intersectiona new set with elements common to all the sets
{1, 2}.intersection({2, 3}) # => {2}
differencea new set with elements in this set but not the others
{1, 2}.difference({2}) # => {1}
symmetric_differencea new set with elements in exactly one of the two sets
{1, 2}.symmetric_difference({2, 3}) # => {1, 3}
issubsetTrue if every element of this set is in the other
{1}.issubset({1, 2}) # => True
issupersetTrue if this set contains every element of the other
{1, 2}.issuperset({1}) # => True
countnumber of items equal to the value
(1, 1, 2).count(1) # => 2
indexindex of the first item equal to the value
(1, 2, 3).index(2) # => 1
bit_lengthnumber of bits needed to represent abs(self) in binary
255 .bit_length() # => 8
conjugatethe complex conjugate; for a real number, self
(5).conjugate() # => 5
is_integerTrue if the float has no fractional part
(3.0).is_integer() # => True