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

Alan Gauld alan.gauld at yahoo.co.uk
Tue Aug 1 14:47:42 EDT 2017


On 01/08/17 15:54, Thomas Güttler wrote:

> He asked me if "if __name__=='main':" is state of the art if you want
> to translate a shell script to python.

It all depends what you plan to do with the script.
If you literally just want to translate a shell script such
that it will always be executed directly then you don't
even need an 'if name' clause, just hard code the script.

But if you plan in writing some functions that could be
reused by importing the script as a module then you really
should use 'if main'...

And if you intend to use your script only as a module
you should still use 'if name'... but this time call a
test function that runs some regression tests and/or
demo code.

But if you want to write a distributable package that
users can install into their Python infrastructure then
you should *additionally* create setup scripts with
entry points etc.

> you want to teach a new comers the joy of python.

For a newcomer I'd ignore packaging for now and focus
on the benefits of 'if name' over hard coding. One of the
great things about Python is how insanely easy it is to
create a file that can act as both a module and
executable. That can be crazy complex in some other
languages by comparison.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list