Alternatively, instead of lambda
, you can use functools.partial which, in my opinion, has a cleaner syntax.
Instead of:
for d in directorys:
self.command["cd " + d] = (lambda d=d: self.root.change_directory(d))
it will be:
for d in directorys:
self.command["cd " + d] = partial(self.root.change_directory, d)
Or, here is another simple example:
numbers = [1, 2, 3]
lambdas = [lambda: print(number)
for number in numbers]
lambdas_with_binding = [lambda number=number: print(number)
for number in numbers]
partials = [partial(print, number)
for number in numbers]
for function in lambdas:
function()
# 3 3 3
for function in lambdas_with_binding:
function()
# 1 2 3
for function in partials:
function()
# 1 2 3