mapLast, mapFirst, and just general iterator questions

Chris Angelico rosuav at gmail.com
Tue Jun 14 15:49:26 EDT 2022


On Wed, 15 Jun 2022 at 05:45, Roel Schroeven <roel at roelschroeven.net> wrote:
>
> Chris Angelico schreef op 14/06/2022 om 20:47:
> > > def main():
> > >     for each in (iterEmpty, iter1, iter2, iterMany):
> > >         baseIterator = each()
> > >         chopFirst = mapFirst(baseIterator, lambda x: x[1:-1])
> > >         andCapLast = mapLast(chopFirst, lambda x: x.upper())
> > >         print(repr(" ".join(andCapLast)))
> >
> > Don't bother with a main() function unless you actually need to be
> > able to use it as a function. Most of the time, it's simplest to just
> > have the code you want, right there in the file. :) Python isn't C or
> > Java, and code doesn't have to get wrapped up in functions in order to
> > exist.
> Not (necessarily) a main function, but these days the general
> recommendation seems to be to use the "if __name__ == '__main__':"
> construct, so that the file can be used as a module as well as as a
> script. Even for short simple things that can be helpful when doing
> things like running tests or extracting docstrings.

If it does need to be used as a module as well as a script, sure. But
(a) not everything does, and (b) even then, you don't need a main()
function; what you need is the name-is-main check. The main function
is only necessary when you need to be able to invoke your main entry
point externally, AND this main entry point doesn't have a better
name. That's fairly rare in my experience.

My recommendation is to write the code you need, and only add
boilerplate when you actually need it. Don't just start every script
with an if-name-is-main block at the bottom just for the sake of doing
it.

ChrisA


More information about the Python-list mailing list