Python Method Placement
Question: Can someone give me a solution to this

    
    
    dosomething()
    
    def dosomething():
        print 'do something'
    

I don't want my method defines up at the top of the file, is there a way
around this?


Answer: The "standard" way is to do things inside a `main` function at the top of your
file and then call `main()` at the bottom. E.g.

    
    
    def main():
        print 'doing stuff'
        foo()
        bar()
    
    def foo():
        print 'inside foo'
    
    def bar():
        print 'inside bar'
    
    if __name__ == '__main__':
        main()
    

if `if __name__ == '__main__':` part ensures that `main()` won't be called if
the file is imported into another python program, but is only called when the
file is run directly.

Of course, "main" doesn't mean anything... (`__main__` does, however!) It's a
psuedo-convention, but you could just as well call it `do_stuff`, and then
have `if __name__ == '__main__': do_stuff()` at the bottom.

Edit: You might also want to see [Guido's advice on writing
`main`'s](http://www.artima.com/weblogs/viewpost.jsp?thread=4829). Also,
Daenyth makes an excellent point (and beat me to answering): The reason why
you should do something like this isn't that is "standard" or even that it
allows you to define functions below your "main" code. The reason you should
do it is that it encourages you to write _modular and reusable_ code.

