[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)

Andrew Barnert abarnert at yahoo.com
Mon Nov 25 00:02:18 CET 2013


From: Greg Ewing <greg.ewing at canterbury.ac.nz>



>G uido van Rossum wrote:
>>  Haven't followed all of this, but perhaps the simplest thing would be 
> to define a new builtin function that returns True in the namespace of the main 
> module and false everywhere else.
> 
> Can someone remind me why there's so much resistance to
> simply blessing a __main__() function? It would be
> straightforward and intuitive and in line with what
> just about every other language does.


Which languages, other than C and its direct descendants?

The other major scripting languages—Ruby, Perl, JavaScript, PHP, Tcl, etc.—have no such thing; they all just execute all the top-level code, and provide some variable you can check to see if you're the "main module", just like Python. The conventional idioms in those languages are mostly borrowed from Python's. For example:

    # Ruby
    if __FILE__ == $0
        exit(main(ARGV)) # or exit(MainClass.new(ARGV).run)
    end

    # Node.js
    if (require.main === module) {
        main(process.argv)
    }

Most functional languages don't have any special main function or main environment. Other procedural languages like Pascal, Fortran, etc. that have a special main environment do it with different syntax—e.g., the code goes in BEGIN PROGRAM instead of in a function/procedure. The only one I can think of that uses a special main function like C is Visual BASIC (which borrowed it from C).


More information about the Python-ideas mailing list