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?
(some_mapping(x) for x in iterable)
. The first one doesn't reallyreduce
anything, its more like a mapping since there is a newsometype
for eachx
. – Quiritesitertools
. Not so complex that they violate basic functional programming principles. For example, they might involve a lot of preliminary setup work as an optimization. – Witten