Skip to content
Advertisement

Define a generator which updates global variables before the first __next__() call

Given the following function in python I would like to update the global variable before calling “next()”. Let me show it to you with an example.

JavaScript

Then you can run:

JavaScript

Which outputs the following:

JavaScript

Finally: please note that there is a way of doing this via a class definition that has a class variable, but I’m currently wondering for a full “functional” implementation.

Thank you for your time

Advertisement

Answer

I’m not entirely sure if I understand correctly what you are trying to do. But the thing is that a generator function in Python only starts to execute once the generator is being enumerated:

JavaScript
JavaScript

So if you want to run code before the generator is being enumerated, you cannot have that code be part of the generator function itself.

What you can do instead is to have a normal function that does something and then returns a created generator:

JavaScript
JavaScript

Since you apparently only set L once, before the first yield, this might be what you want to do.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement