calling functions style question

B

Brian

I just have a basic style question here. Suppose you have the program:

def foo1():
do something

def foo2()
do something else

Assume that you want to call these functions at execution. Is it more
proper to call them directly like:

foo1()
foo2()

or in an if __name__ == "__main__": ?

Both will execute when the script is called directly, I was just
wondering if there is a preference, and what the pros and cons to each
method were.

Thanks,
Brian
 
T

Thomas Nelson

The difference becomes clear when you import your program into another
program (or the command line python editor). __name__!='__main__' when
you import, so the functions will not be called if they're inside the
block. This is why you see this block so often at the end of scripts;
so that the script runs its main functions when called as a standalone
program, but you can also import the code and do something with it
without setting off those functions.

THN
 
K

Kay Schluehr

Brian said:
I just have a basic style question here. Suppose you have the program:

def foo1():
do something

def foo2()
do something else

Assume that you want to call these functions at execution. Is it more
proper to call them directly like:

foo1()
foo2()

or in an if __name__ == "__main__": ?

Both will execute when the script is called directly, I was just
wondering if there is a preference, and what the pros and cons to each
method were.

Thanks,
Brian

If you want those functions to be called each time your module gets
imported you have to apply calls out of the "if __name__ ..."
statement. If your module is, for certain reasons, always the __main__
module and never gets imported there is no obvious preference because
behaviour will be the same.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top