Question

Most functions are easy to name. Generally, a function name is based on what it does or the type of result it produces.

In the case of a generator function, however, the result could be a iterable over some other type.

def sometype( iterable ):
    for x in iterable:
        yield some_transformation( x )

The sometype name feels misleading, since the function doesn't return an object of the named type. It's really an iterable over sometype.

A name like iter_sometype or gen_sometype feels a bit too much like Hungarian Notation. However, it also seems to clarify the intent of the function.

Going further, there are a number of more specialized cases, where a prefix might be helpful. These are typical examples, some of which are available in itertools. However, we often have to write a version that's got some algorithmic complexity that makes it similar to itertools, but not a perfect fit.

def reduce_sometype( iterable ):
    summary = sometype()
    for x in iterable:
         if some_rule(x): 
             yield summary
             summary= sometype()
         summary.update( x )

 def map_sometype( iterable ):
     for x in iterable:
         yield some_complex_mapping( x )

 def filter_sometype( iterable ):
     for x in iterable:
         if some_complex_rule(x):
              yield x

Does the iter_, map_, reduce_, filter_ prefix help clarify the name of a generator function? Or is it just visual clutter?

If a prefix is helpful, what prefix suggestions do you have?

Alternatively, if a suffix is helpful, what suffix suggestions do you have?

Was it helpful?

Solution

Python dicts have iter* methods. And lxml trees also have an iter method. Reading

for node in doc.iter():

seems familiar, so following that pattern, I'd consider naming the a generator of sometypes sometypes_iter so that I could write analgously,

for item in sometypes_iter():

Python provides a sorted function. Following that pattern, I might make the verb-functions past tense:

sometypes_reduced
sometypes_mapped
sometypes_filtered

If you have enough of these functions, it might make sense to make a SomeTypes class so the method names could be shortened to reduce, map, and filter.

If the functions can be generalized to accept or return types other than sometype, then of course it would make sense to remove sometype from the function name, and instead choose a name that emphasizes what it does rather than the types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top