Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Method Placement

Tags:

python

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?

like image 281
shawn Avatar asked Oct 14 '10 20:10

shawn


People also ask

Does the order of methods matter in Python?

So in general, yes, the order does matter; there's no hoisting of names in Python like there is in other languages (e.g JavaScript).

Where should functions be placed in Python?

Defining a FunctionFunction blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

What is correct order of execution about class and object in Python?

It executes the code inside a class only when it is "called", not when it is defined. So, the output should print "Out" first. But here it is printing "Middle" first. This should not happen, as python interpreter when first encounters "Middle" - it is within the definition, and thus should not be executed at that time.

Can a function be defined anywhere in Python?

Anywhere in your application that you need to accomplish the task, you simply call the function. Down the line, if you decide to change how it works, then you only need to change the code in one location, which is the place where the function is defined.


1 Answers

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.

like image 121
Joe Kington Avatar answered Oct 16 '22 05:10

Joe Kington