[Tutor] if __name__=='main' vs entry points: What to teach new comers?

Ben Finney ben+python at benfinney.id.au
Tue Aug 1 21:22:00 EDT 2017


Steven D'Aprano <steve at pearwood.info> writes:

> On Tue, Aug 01, 2017 at 04:54:40PM +0200, Thomas Güttler wrote:
>
> [...]
> > I use Python since several years and I use console_script in
> > entry_points of setup.py.
>
> What's console_script in entry_points of setup.py?

It is an advanced feature in Setuptools, that allows defining a function
in the code base as the entry point for external use.

The “console_scripts” entry points tell Setuptools to, at installation
time, create a wrapper script that invokes that function as a
command-line program.

    <URL:https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation>

> I think if you are teaching newcomers about packaging and setup.py,
> they will probably decide that Python is too complicated and hard to
> use.

Also, if you are teaching packaging and you introduce Setuptools
entry_points, they will probably decide that Setuptools is too
complicated and hard to use.

So I agree with Steven that teaching *newcomers to Python* how to use
Setuptools entry points is far too advanced level.

> For slightly more advanced use, move the script's executable code into
> a function, and test whether we're being imported or run as a script
> before calling the function:
>
>
> #!/usr/local/bin/python3
> def main():
>     print("Hello world!")
>
> if __name__ = '__main__':
>     main()

That's the best, I agree. Teach them early on to put all functionality
into functions, and (since the OP informs us these are accustomed to
writing command-line programs) the ‘if __name__ == '__main__'’ idiom
will be easy enough.

They should definitely learn it from you, along with the admonition to
*always* keep that block as small as possible.

Better than learning the idiom independently later on, and cramming half
their program into that block :-/

-- 
 \            “But it is permissible to make a judgment after you have |
  `\    examined the evidence. In some circles it is even encouraged.” |
_o__)                    —Carl Sagan, _The Burden of Skepticism_, 1987 |
Ben Finney



More information about the Tutor mailing list