ruk·si

🐍 Python
nonlocal

Updated at 2018-06-10 22:53

You need to use nonlocal if you are changing immutable variable in another closure than where it was defined. Rarely makes sense though.

from typing import Callable

def make_averager() -> Callable[[float], float]:
    count = 0
    total = 0

    def averager(new_value: float) -> float:
        nonlocal count, total
        count += 1
        total += new_value
        return total / count

    return averager

avg = make_averager()
assert avg(10) == 10
assert avg(11) == 10.5
assert avg(12) == 11

Source

  • Fluent Python, Luciano Ramalho