[Tutor] Notepad++ question

Alexander Quest redacted@example.com
Fri Jun 15 07:45:54 CEST 2012


Thanks Walter; I believe I understand the reasoning behind it, though not
all of the mechanics, but for now, your answer is more than sufficient.

-Alex

On Thu, Jun 14, 2012 at 4:10 PM, Walter Prins <wprins at gmail.com> wrote:

> Hi Alex,
>
> On 14 June 2012 23:18, Alexander Quest <redacted@example.com> wrote:
> > if __name__ == '__main__':
> >   main()
> >
> > This calls the main function, but I don't understand what the 'if'
> statement
> > is doing here. In the simple programs that I've seen this so far, there
> is
> > no variable called "_name_", and even if there was, why is it comparing
> it
> > to "_main_"? Why can't the main function just be called by typing main()-
> > why do we need this if statement to precede it? Thanks.
>
> In short, consider the implications of the fact that your file, apart
> from being a program that can run standalone, might also be a Python
> module that might be used in another program.  Oftentimes you want to
> write your Python code in such a way that when the module is run
> directly you want it to do something useful (such as run a main()
> function, e.g. maybe run some unit/self-tests or whatever), while when
> you import it for use in another program/module then you probably
> rather do *not* want it to run as if it is itself the "main program".
> So, in order to differentiate the 2 cases, there exists the above
> Python idiom.  So, when a module is directly run as the "main
> program", then the name of the module being run, which is reflected by
> the variable __name__, made available by the Python interpreter, will
> be equal to "__main__", while when it's imported it will be equal to
> the module name.  This allows your module to know when it's running
> whether it's running as the main program or just running because it's
> been imported by another module.
>
> Does that answer your question?
>
> Walter
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120614/e77e6b43/attachment.html>


More information about the Tutor mailing list
html>