[Python-ideas] Catching the return value of a generator at the end of a for loop

Stefano Borini stefano.borini at gmail.com
Wed Apr 17 02:58:07 EDT 2019


On Wed, 17 Apr 2019 at 00:45, Steven D'Aprano <steve at pearwood.info> wrote:
> I don't know. You tell us -- why do you care about the StopIteration
> value in a for-loop?

I came across the idea while I was reading various PEPs, so I don't
have an actual use case under my hands right now. However, in the past
I had a circumstance that might have called for that. Of course it was
easy to workaround.
I was iterating over plugins as they were loaded, using a generator,
and setting up some configuration options. e.g.

def load_plugins():
  for plugin in pluginloader:
     if plugin.success:
         plugin.setup(configuration_vars)

In some cases, some of the plugins failed to load (e.g. because there
was a syntax error in their content). In my design, the plugin class
instance had a flag indicating if it was successful or not
(plugin.success).

I wanted to keep track of how many plugins failed to load and how many
were successful, so I could return that information to the user. This
calls for counting at the level of load_plugins(). If pluginloader
returned a tuple (num_successful, num_failed) it would save a (agreed
trivial) need to count this information in the caller.



-- 
Kind regards,

Stefano Borini


More information about the Python-ideas mailing list