returnAdvanced Examples

Exits a function and optionally sends a value back to the caller

Return as a first-class pattern

Returning functions, classes, and complex objects.

python
def make_adder(n):
    def adder(x):
        return x + n
    return adder

add5 = make_adder(5)
add10 = make_adder(10)
print(add5(3))
print(add10(3))

# Returning a class
def make_class(name, fields):
    def init(self, **kwargs):
        for f in fields:
            setattr(self, f, kwargs.get(f))
    def repr_(self):
        vals = ", ".join(f"{f}={getattr(self, f)!r}" for f in fields)
        return f"{name}({vals})"
    cls = type(name, (), {"__init__": init, "__repr__": repr_})
    return cls

Point = make_class("Point", ["x", "y"])
p = Point(x=1, y=2)
print(p)
Expected Output
8
13
Point(x=1, y=2)

Functions are first-class objects, so you can return functions (closures), classes, or any other object from a function.

Want to try these examples interactively?

Open Advanced Playground