[Chicago] __name__ == "__main__"
andrew at humanized.com
Fri Oct 26 17:59:17 CEST 2007
The goal of this bit of indirection is (I think) born of an impulse that
runs strong in people who write lots and lots of production quality Python
Never put code that actually does stuff in the global scope.
I know in my own code, and ours here at work, we tend to obey that pretty
strongly. In fact, almost every single global variable is initialized to
None, and does not get assigned a value until some kind of "main()" function
is run (in the case of scripts) or "init()" (in the case of modules). This
simply dodges the question of when code gets executed, which is a bit
strange with multiple imports of a single module lying around; code that
initializes variables, etc. gets called when the "main()" or "init()"
function is executed, so you can maintain clearly defined control over when
I'm not saying that this indirection makes even the remotest bit of sense
for scripts where there is code that will only be run if the module is
executed as a script, but the instinct runs strong. Anything you cram into a
function can theoretically be unit-tested (or integration-tested); code that
executes in the global scope cannot be (without doing a dance of subprocess,
by-the-way my current favorite Python module).
On 10/26/07, Michael Tobis <mtobis at gmail.com> wrote:
> I agree with everything Kumar says. It could be prettier, but it's
> extremely useful to put the
> __name__ == "__main__" around code in your file that doesn't define
> objects or functions.
> Now that it's come up, though. what I never quite understood was the
> extra level of indirection that many people including Guido favor.
> def invoke_lots_of_stuff():
> print "I represent a lot of very clever objects and functions"
> def main():
> if __name__ == "__main__":
> What's the purpose of the extra layer provided by the main() function?
> Also, yeah, there's a little bit of a Python activity in Chicago...
> (Miss y'all; looking forward to seeing you again in March.)
> Chicago mailing list
> Chicago at python.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Chicago