0

I was wondering what does if __name__ == "__main__": really do in python, I have the following code in python3:

def main():
    test();

def test():
    print("hello world " + __name__);

if __name__ == "__main__":
    main();

we know that we have to declare a function before we use it, so function call inside of if part works fine, the main() is defined before it is called inside of if statement, but what about the test() function, it is defined after it is called and there is no errors:

def main():
    test();

def test():
    print("hello world " + __name__);

so how could it works if the test() function is defined after it is called?

user2131316
  • 3,111
  • 12
  • 39
  • 53
  • http://stackoverflow.com/questions/419163/what-does-if-name-main-do?rq=1 – Paul H Nov 12 '13 at 21:35
  • I read that link, but it does not answer my question, so I ask a new question – user2131316 Nov 12 '13 at 21:37
  • You chose a bad title for your question, which causes it to be closed. I think your question is valid, but judging by the title alone, it is not (for being a duplicate)... – shx2 Nov 12 '13 at 21:39
  • You have two separate questions here. Your first one—the one in your title—is very definitely answered by that question. The second one—how `test` works—is not. And that's why you should write each separate question as a separate question: so each one can be answered or usefully closed, instead of all but the first one being ignored by most of the community. – abarnert Nov 12 '13 at 21:40
  • Well, `test()` is under the function `main()` & `main()` DOES NOT get executed until it is called. Thus, if you declare `test()` after calling `main()` then it will give you `NameError`. But, if you define `test()` before calling `main()` (in which `test()` is called), the code will work. – shad0w_wa1k3r Nov 12 '13 at 21:40
  • @user2131316 I'm voting to reopen, the issue is that you've misidentified what the problem is. Your question has nothing to do with `if __name__ == "__main__":` and everything to do with what the python interpreter does when it compiles functions. – roippi Nov 12 '13 at 21:41
  • @user2131316: If you edit this question to be about your second question instead of the duplicate first question, I'm pretty sure it will get reopened. – abarnert Nov 12 '13 at 21:41
  • 1
    Changed the title, and voting to reopen. – Robᵩ Nov 12 '13 at 21:42
  • I changed the question title and voted to reopen, what else can I do? – user2131316 Nov 12 '13 at 21:46
  • Voila! It is reopened. – Robᵩ Nov 12 '13 at 21:46
  • 1
    "*we know that we have to declare a function before we use it*" - Whoever taught you that, lied. – Robᵩ Nov 12 '13 at 21:48
  • Wow. How do you mark 2 duplicates!? :P – shad0w_wa1k3r Nov 12 '13 at 21:48
  • @Robᵩ: Well, you do have to _define_ a function before you use it. (There's really no such thing as "declaring" in Python—that whole declare/define distinction only makes sense in languages like C-style variables-as-typed-memory-locations…) The reason it works is that he _is_ defining the function before he uses it. – abarnert Nov 12 '13 at 21:56
  • @abarnert - precisely. – Robᵩ Nov 12 '13 at 21:57

4 Answers4

5

Test is not defined after it is called. The order is:

  1. Define main. This references a (yet undefined) test, but does not actually use (call) it. Python is ok with that.
  2. Define test.
  3. Call main.
  4. main calls test. No problem, as it is already defined.
oefe
  • 19,298
  • 7
  • 47
  • 66
1

The issue here really has nothing to do with if __name__ == 'main'. Consider the following code:

def do_something():
    do_something_else()

The above is a valid function declaration. Even if I haven't written do_something_else() yet. Feel free to try this out in your interactive interpreter. Now, when I actually call do_something():

do_something()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-21-3d57cd7a951b> in <module>()
----> 1 do_something()

<ipython-input-20-5d71722aad44> in do_something()
      1 def do_something():
----> 2     do_something_else()
      3 

NameError: global name 'do_something_else' is not defined

It errors out. It would not if, at some point at any time before invoking do_something(), I had defined my do_something_else function.

So, what does this mean? Python does indeed interpret top-to-bottom. But when a function definition is reached, it merely compiles the function, it does not execute it.

roippi
  • 25,533
  • 4
  • 48
  • 73
0

Python executes code in the order it sees it.

You type in def main(): it takes it as a function definition to be run later.

The if __name__ == "__main__": checks if the current file is the one that is supposed to be run (as opposed to included). and in that case it will execute whatver is below (usually main)

You can put something like this:

print "here"
def main():
  print "in main"

if __name__ == "__main__"
  main()

and you should see an output like

here
in main

This is because python is intrinsically a scripting language and functions are optional. That being said for any piece of code that's not meant to be thrown away in the next 10 minutes you should use functions and classes. They make the code easier to understand follow and debug.

The reason your particular code works (with test defined after main) is that you run it after everything is defined. Python will not attempt to check if there's a test to be called unless you run main. When you run main, test has already been defined.

Sorin
  • 11,863
  • 22
  • 26
0

we know that we have to declare a function before we use it

It sounds like you're coming from a language in the C family. These languages are different in two ways.

First, Python doesn't "declare" anything. That makes sense in languages like C, where variables are typed memory locations that values get stored in. But in Python, values have their own independent types and locations, and variables are just names for those values, so there is nothing to declare.

Now, Python requires you to define a function before you use it, just like C.

But only C also requires you to define, or at least declare, a function before you compile a function whose body uses it. The difference is the same as above—C needs the function to be declared, to get the types, the pointer to the function's actual code, etc.; in Python, the function is just a name for the function-object value. To compile a function, all it needs to know is where to look up the names. And that's easy: it compiles the function so that, at runtime, it will look up the name in the module globals. Since no other information is needed, there's nothing to declare.

For example, in C, this is legal:

void foo() {}
void bar() { foo(); }

And so is this:

void foo();
void bar() { foo(); }
void foo() {}

But this is not:

void bar() { foo(); }
void foo();

In Python, because there are no declarations, the second and third are identical, and therefore both perfectly valid:

def bar():
    foo()
def foo():
    pass
abarnert
  • 354,177
  • 51
  • 601
  • 671