Python Glossary Русский

Python 3.8+typesterm

types.CellType

interpreter objects

The type of a closure cell: it holds a variable of the outer function that the inner function sees. Cells live in func.__closure__.

Syntax

func.__closure__[0].cell_contents

A cell holds the variable, not its value at the moment the function was created. That is the famous trap: lambdas made in a loop share one cell i and after the loop they all see the last value. The content is read through cell.cell_contents. The fix is a default value (lambda i=i: i), which is evaluated immediately, or functools.partial.

Examples

import types
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])  # → [2, 2, 2]
cell = funcs[0].__closure__[0]
print(isinstance(cell, types.CellType), cell.cell_contents)  # → True 2
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])  # → [0, 1, 2]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy