Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python closures and cells (closed-over values)

What is the Python mechanism that makes it so that

[lambda: x for x in range(5)][2]()

is 4?

What is the usual trick for binding a copy of x to each lamba expression so that the above expression will equal 2?


My final solution:

for template, model in zip(model_templates, model_classes):
    def create_known_parameters(known_parms):
        return lambda self: [getattr(self, p.name)
                             for p in known_parms]
    model.known_parameters = create_known_parameters(template.known_parms)
like image 538
Neil G Avatar asked Dec 16 '22 04:12

Neil G


1 Answers

>>> [lambda x=x: x for x in range(5)][2]()
2
like image 187
Lauritz V. Thaulow Avatar answered Dec 23 '22 06:12

Lauritz V. Thaulow