How am I doing?

Tom Anderson twic at urchin.earth.li
Tue Sep 20 06:06:42 EDT 2005


On Mon, 19 Sep 2005, Brett Hoerner wrote:

> Wouldn't the standard idiom be to actually put the code under the 
> if-name, and not make a whole new main() function?

Yes.

The nice thing about the main() function, though, is that you can do the 
most basic argument parsing in the if-block. Like so:

def powers(n):
 	m = 1
 	while True:
 		yield m
 		m = m * n

def main(n, limit):
 	for power in powers(n):
 		if (power > limit): break
 		print power

import sys

if (__name__ == "__main__"):
 	main(int(sys.argv[1]), int(sys.argv[2]))

That serves as a sort of documentation on the arguments to the script, and 
also makes it easier for other scripts to reuse the main logic of the 
program, since they don't have to package parameters up as a string array. 
It is more verbose, though.

> I'm not sure I see the reason behind main(), couldn't that also 
> interfere with other modules since main() seems like it might be common, 
> not sure how it would work as I'm pretty new to Python myself.

The two mains would be in different namespaces, so they wouldn't conflict.

> from script import *

Don't do that. 'from script import x' is, IMNERHO, bad practice, and 'from 
script import *' is exceptionally bad practice. I know a lot of people do, 
but that doesn't make it right; namespaces are there for a reason.

tom

-- 
Science runs with us, making us Gods.



More information about the Python-list mailing list