开发者

Order of execution and style of coding in Python

I am new to Python so please don't flame me if the question is too basic :)

I have read that Python is executed from top - to - bottom.

If this is the case, why do programs go like this:

def func2(): 
    pass

def func1():
    func2()

def func():
    func1()

if __name__ == '__main__':
    func()

So from what I have seen, the main function goes at last and the other functions are stacked on top of it.

Am I wrong in saying this? If no, why isn't the main function or the function definitions written from top to bottom?

EDIT: I am asking why I can't do this:

if __name__ == '__main__':
    func()

def func1():
    func2()

Isn't this the natural order? You keep on adding stuff at the bottom, since it is 开发者_如何转开发executed from top to bottom.


The defs are just creating the functions. No code is executed, other than to parse the syntax and tie functions to those names.

The if is the first place code is actually executed. If you put it first, and call a function before it is defined, the result is a NameError. Therefore, you need to put it after the functions are defined.

Note that this is unlike PHP or JavaScript, where functions are 'hoisted' - any function definitions are processed and parsed before everything else. In PHP and JavaScript, it's perfectly legal to do what you are saying and define functions in the source lower down than where they are called. (One detail in JS is that functions defined like function(){} are hoisted, while functions defined like var func1=function(){}; are not. I don't know how it works with anonymous functions in PHP 5.3 yet).

See, in this, cat() will print correctly, and yip() gives you a NameError because the parser hasn't gotten to the definition of yip() at the time you call it.

def cat():
  print 'meowin, yo'

cat()

yip()

def yip():
  print 'barkin, yall'

meowin, yo
Traceback (most recent call last):
File "cat.py", line 5, in
yip()
NameError: name 'yip' is not defined


Python is executed from top to bottom, but executing a "def" block doesn't immediately execute the contained code. Instead it creates a function object with the given name in the current scope. Consider a Python file much like your example:

def func2():
    print "func2"

def func1():
    func2()

def func():
    func1()

if __name__ == '__main__':
    func()

What happens when this script is executed is as follows:

Firstly, a function object is created and bound to the name "func2" in the global scope. Then a function object is created and bound to the name "func1" in the global scope. Then one called "func". Then the "if" statement is executed, the condition is true and the "func()" statement is executed. At this point "func" is a function object found in the global scope, so it is invoked and its code runs. That code contains the "func1()" statement, which is resolved to a call to the "func1" function, and so on.

If you put the "if" statement at the top then when it executes there would not yet be anything defined with the name "func", so you would get an error. The important thing to recognise is that the "def" statement is itself a statement that is executed. It is not like in some other languages where definitions are a separate sort of declaration with no order of execution.

Also note that so long as the "if __name__..." bit is at the end of the file, it doesn't really matter what order the other declarations are in, since by the time any of them are called all of the "def"s will have already been executed.


Python does, in general, process commands from top to bottom. However, a function call will cause Python to execute that function, and continue downward only after that call has ended.

In your example, the Python interpreter executes the following steps:

  1. Define func2.
  2. Define func1.
  3. Define func.
  4. Process if statement if __name__ == '__main__':.
  5. Call the func function (since the condition is true).
  6. Call the func1 function (because that's what func does).
  7. Call the func2 function (because that's what func1 does).
  8. End, because after finishing the call to func2 it has also finished calling func1 and therefore has finished calling func, which was the final statement in the code.


It's also worth noting that you can have function calls written occur "before they're defined", as long as they aren't executed. Mentioning this here as it's a common new-to-python error. None of the other examples demonstrate this "it's ok, in one way" behavior. (though not really recommended)

def hi():
  pie()

#hi() cannot be called here, doesn't work because hi depends on pie

def pie():
  print('hi pie')

hi() # it's ok to call here!

You can even go a little further (slightly silly example, but I believe it clarifies the example)

runIt = False
def hi():
  if runIt:
    pie()

hi() #now ok, as the code won't call pie.
runIt = True
#hi() #wouldn't be ok as now the code will call pie.

def pie():
  print('hi pie')

hi() # ok here too!


The if __name__ == "__main__" part goes at the end, because presumably whatever your main function does will need all the other definitions in the script. If there were any other function definitions below the main block, then it would not be possible for them to be used in there, since they haven't been seen by the interpreter at that point.


def statements simply define a function - they don't actually run it until the function is invoked. Hence why they generally come before whatever code uses them - they set the function up to be used in the future.

There's no hard requirement that def statements come before anything else, it's just fairly common to put the __main__ code at the bottom (among other things, it makes it clear what's in that section and what isn't, since anything below the if is part of that section). It also makes sure whatever you want to call from the section has already been def'd.


For the second part of your question (Style of coding in Python), I would take a look at PEP 8, which provides a style guide written by Guido van Rossum (the BFDL himself!) and provides the basics of writing Pythonic code.


It's true that the convention is to put the "main" function just above the "if __name__ == '__main__'" statement at the end of the file. I think that this is because we usually want functions to be near to their calling sites.

As for the called function coming above the calling function, I think that this is just a result of refactoring. At least in my case, I tend to write a function, and then take out bits of code to put into sub-functions, which I put on top so that I can see better.

This is just a primitive form of code organization. If there's a stronger cohesive unit, I'd be tempted to pull those functions into their own module.


There is two points that you need to know :

  1. The main condition is to block the prevent code from being run when the module is imported. In our case, the condition is true because our file is not imported.
  2. The code is working as follows :
    • Define func2
    • Define func1
    • Define func
    • Process if statement if __name__ == '__main__': (which in our case is True)
    • Call the func function
    • Call the func1
    • Call the func2 function
    • return the result(print the message func2)
    • End
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜