Dec-14-2022, 02:00 AM
(Dec-13-2022, 07:00 PM)deanhystad Wrote:(Dec-13-2022, 06:06 PM)cametan_001 Wrote: This seems a sort of pit fall; thus I would watch out when I use a generator.When you do this:
stream = filter(lambda x: x % head != 0, stream)Python creates a closure that contains the variable "head" and the anonymous function generated by the lambda expression.
def anoinymous(x): return x % head != 0When the lambda expression is in your iterator, the variable "head" is different for each closure because each call to __next__(self) creates a new "head" variable.
When the lambda expression is in your generator, the variable "head" is the same for each closure because you never leave the generator scope.
You should probably use this notation for your iterator to prevent having to create a closure for each lambda.
stream = filter(lambda x, y=head: x % y != 0, stream)This creates an anonymous function that kind of looks like this:
def anonymous(x, y=2): return x % y != 0No need now for a closure because we don't use any variables, only function arguments.
Thanks for the detailed explanation!
I tried some experiments like making a local function:
def anoinymous(x): nonlocal head return x % head != 0, put it in the filter, and saw what is going on; however, as a result, what you showed is the only way to be succeess.
Anyway, thank you very much!