Name of a function returning a generator


How do you name a function that returns a generator (that is, uses yield foo instead of return foo)?

  • It’s definitely not getFoo() because it does not return a value of Foo.
  • It’s probably not foos() because I’d rather have an easy-to-distinguish prefix.
  • It’s probably not exactly listFoo() because it does not return a list.
  • It’s probably not iterateFoo() because this prefix is too long.

What’s your preferred solution?


While foos() may be a perfectly good solution in some cases, note how method names tend to begin with a verb. The verb conveys the idea that this is a method, not a data field, and thus helps readability. If possible, I’d prefer a solution that makes it easy to tell a method from a data field.

Asked By: 9000




(…and some extra words ensure this solution has at least 30 characters)

Answered By: Gerrat

Some terse suggestions:


Since you don’t normally need a generator to just get all your foos, it’s pretty common for the specific function of the generator to suggest a more interesting name:

Answered By: Russell Borogove

I think foo or foos are possibilities. Or, to mimic Python2 dicts’ iteritems, you could use iterfoo.

Answered By: unutbu

Although it is good practice to have helpful names that indicate what things do, I do not think it is at all necessary to use Hungarian notation to indicate the return type of a function.

The return type should probably be documented in comments or the docstring, but I would suggest that something like foos(), getfoos(), or get_foos() would be best for the name.

If you do want it to be obvious that this is a generator, I would suggest iterfoos() for its similarity to Python 2’s dict methods like itervalues().

Keep in mind that many built-in functions that used to return lists are now generators in Python 3 (map(), dict.values() etc.), so it should not surprise anyone when your functions that return a sequence are generators even if you didn’t call it generate_foos() or some other variation.

Answered By: Andrew Clark

The most accurate would be:


You say specifically what the function does while being pretty clear why you would use it.

Answered By: Catskul
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.