CKTIS / Python
Keyword def
Executing def creates a function, and its name receives the result of any decorators, which can replace it.
Version: Python 3.14; repository image, production runtime not attested
Syntax
def quote(units, /, *, rate=2):
return units * rateExecuting def creates a function, and its name receives the result of any decorators, which can replace it.
Since Python 3.12 def first[T] introduces a type parameter. The body of an ordinary function runs only at call time. Default expressions are evaluated once when the definition executes, so a mutable default can retain state across calls. A slash marks positional-only parameters and a lone star introduces keyword-only parameters.
The example passes a separate list to isolate one call.
Examples
def collect(item, /, *, bucket=[]):
bucket.append(item)
return tuple(bucket)
print(collect("a"), collect("b"), collect("c", bucket=[]))
try:
collect(item="d")
except TypeError:
print("positional only")
trace = []
@lambda fn: (fn, "wrapped")
def first[T](x: T) -> T:
trace.append("called")
return x
fn, tag = first
assert trace == [] and tag == "wrapped" and fn.__type_params__[0].__name__ == "T"
assert fn(3) == 3 and trace == ["called"]
Result
('a',) ('a', 'b') ('c',)
positional onlyThe example passes a separate list to isolate one call.