简体   繁体   中英

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?

Update:

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.

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

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.

The most accurate would be:

iterateFoo()
iterate_foo()
iter_foo()
iterFoo()

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

Some terse suggestions:

getFoos()
generateFoos()
yieldFoos()
allFoos()

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:

getActiveFoos()
getGreenFoos()
getFoosMatchingCriteria(someCriteria)
getFoosOverTheNetworkIfTheDatabaseIsntBeingAJerkface()

genFoo()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM