How to make an empty generator?

Stephen Hansen apt.shansen at
Fri Feb 19 00:37:09 CET 2010

On Thu, Feb 18, 2010 at 3:08 PM, Steven D'Aprano <
steve at> wrote:

> On 2010-02-18 16:25 PM, Stephen Hansen wrote:
> > The only way I can figure out how to make an empty generator is:
> >
> >      def gen():
> >          # do my one-time processing here
> >
> >          return
> >          yield
> If all you want is a generator that doesn't yield anything, then surely
> there isn't any one-time processing and you don't need the comment?

Its possible I didn't explain myself well. I don't want a generator that
does /nothing at all/, but a generator that yields nothing.

Basically, I have a core system that loads up a bunch of modules
dynamically. The API of these modules is that their initialization function
is a generator that yields objects that the core system juggles. For the
majority of the cases, this is just fine.

A couple modules though, just really need to do a one-time action, and
everything's done. I /could/ change the initialization function to return a
generator, and not be a generator itself, and check if its None or not, etc.
But I don't really want to, as I like the API the way it is.

So really, the above generator looks like:

def initialize():
    os.environ["BLAH"] = 5


In that its doing a single side-effect action and that's it.

> >> Is there a better way? The return/yield just makes me flinch slightly.
> Meh. An empty generator is a funny thing to do, so it's not bad that it
> reads a bit funny. I don't have a problem with it.

It doesn't -really- annoy me, it just makes me flinch slightly, and that's
very rare. Even the stranger things to do in Python rarely make me flinch.
So I was wondering if I missed something basically, and if there's a proper
way to do it.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list