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

Steven D'Aprano steve at pearwood.info
Tue Aug 1 21:10:54 EDT 2017


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?

In particular, what does that have to do with writing an executable 
script?

setup.py is used for packaging Python code, so it can be distributed and 
installed easily.


> I am very unsure if this is the right way if you want to teach a new comers 
> the joy of python.

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.

For beginners, the best way to write a script is to just put your code 
in a file with a hashbang line.


#!/usr/local/bin/python3
print("Hello world!")



chmod the file to executable, and the script is ready.


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()



This is considered best practice because it allows you to import the 
script for testing without the main() function automatically running.

When Python imports your script, the special variable __name__ will be 
set to the name of the script. When Python executes the script, __name__ 
will be set to the literal string '__main__'.



-- 
Steve


More information about the Tutor mailing list