shawn
shawn

Reputation: 341

Python Method Placement

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?

Upvotes: 5

Views: 4477

Answers (2)

Joe Kington
Joe Kington

Reputation: 284760

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. 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.

Upvotes: 14

Sean Vieira
Sean Vieira

Reputation: 160005

Aside from adding the definition of dosomething to a separate file and importing it:

from my_module import dosomething

dosomething()

I don't believe there is any other way ... but I could be wrong.

Upvotes: 3

Related Questions