Menu
CoddyTech

Scope and Callable Objects

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

Pass a Python function directly as an object and call it with parentheses. Java lambdas target functional interfaces; Python lambdas create function objects and contain one expression only. Use def for statements or multiple operations. Assignment in a function normally creates a local binding; global targets a module binding, and nonlocal targets an existing enclosing-function binding. Mutation of a shared list is different from rebinding the name. Java local variables captured by lambdas must be final or effectively final; Python closures use different binding rules.

Java excerpt: inside main

java.util.function.IntUnaryOperator twice = x -> x * 2;
System.out.println(twice.applyAsInt(4));

Python

def transform(values, callback):
    return [callback(value) for value in values]
print(transform([4], lambda x: x * 2))

Watch the difference

Java braces introduce local scopes; ordinary Python if/for suites do not. A Python comprehension has its own iteration-variable scope. Calling a callback twice per item can break callers with counters or other side effects.

Practice

Apply this comparison in the task below. Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

challenge icon

Challenge

Beginner

Implement transform_all(values, transform): call the callback once for each original element in order and return a fresh result list. Preserve the input list. The driver uses addition-by-three and negation callbacks, prints both results and call counts, reports argument-order correctness, then prints unchanged or changed. Python callable objects can be passed directly where Java uses a functional interface.

Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

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 Java Developers

Practice on your own: Online Python compiler