Menu
CoddyTech

Captured Values and Callables

Lesson 25 of 48 in Coddy's Python for GDScript Developers course.

A GDScript lambda captures local scalar values at creation. Python closures look up outer bindings when called, so later rebinding can change the result. GDScript invokes a stored Callable with call; Python function values are directly callable with parentheses. Python lambda is a single expression. Use a default argument when a Python callback must retain the current value.

GDScript

extends SceneTree
func _init():
    var factor = 2
    var scale = func(x): return x * factor
    factor = 3
    print(scale.call(4))
    quit()

Python

factor = 2
scale = lambda x: x * factor
factor = 3
print(scale(4))

Porting trap

GDScript captured Arrays can still share mutable contents, so scalar capture is not a universal deep-copy rule. Python nonlocal is required when rebinding an enclosing function's name, but not when merely reading it.

Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.

challenge icon

Challenge

Beginner

Implement transform_all(values, transform). Call the supplied one-argument function exactly once per list element, in encounter order, and return a new list of its results. Preserve values. Do not print. The locked driver reads integer tokens on one line. It calls your function with two different callbacks: adding 3 and negating. It prints both result lists, then both callback counts on one line. Next it prints True if both callbacks received exactly the original elements in order, and finally unchanged or changed for the input list.

Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.

Try it yourself

from functions import transform_all

values = [int(part) for part in input().split()]
before = values.copy()
plus_calls = []
negative_calls = []
def plus(value):
    plus_calls.append(value)
    return value + 3
def negative(value):
    negative_calls.append(value)
    return -value
print(transform_all(values, plus))
print(transform_all(values, negative))
print(len(plus_calls), len(negative_calls))
print(plus_calls == before and negative_calls == before)
print("unchanged" if values == before else "changed")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for GDScript Developers

Practice on your own: Online Python compiler