What does __name__ actually do in python?
<p>First of all I have to say, that I'm not new in Python. I know the <em>use</em> of <code>if __name__ == '__main__':</code> well enough. I just try to understand <em>how</em> the Python interpreter handles this. I wrote two scripts to test what's possible in Python. Note that that's actually really bad Python - I wouldn't make use of such things. I only want to learn about the <em>possibilities</em>.</p>

<p>main.py:</p>

<pre><code>import bad.py


def main():

    print "Hello, World!"


if __name__ == '__main__':

    main()
</code></pre>

<p>bad.py:</p>

<pre><code>__name__ = '__main__' # I expected an Error caused by this line


def main():

    exit() # I know that this function shouldn't be used


if __name__ == '__main__':

    main()
</code></pre>

<p>There's no output by running <code>main.py</code> and I didn't really expect an output.</p>

<p><strong>what I want to know:</strong></p>

<ul>
<li>does <code>__name__ = '__main__'</code> in <code>bad.py</code> automatically change the variable <code>__name__</code> in <code>main.py</code>? Or can two <em>different</em> <code>'__main__'</code>-modules exist?</li>
<li>is it possible to substitute an <code>import</code> statement just by manipulating <code>__name__</code>? If it is, how would you do that?</li>
<li><p>when I change <code>exit()</code> to <code>print "Hello",</code>, The output is <code>"Hello"</code>, then an Error occurs:</p>

<pre><code>Traceback (most recent call last):
  File "main.py", line 1, in &lt;module&gt;
    import bad.py
ImportError: No module named py
</code></pre>

<p>could someone explain this behaviour?</p></li>
<li>Are there any differences between python versions / operating systems? I tried this example in Python 2.7.6 on Linux2</li>
</ul>

<p><strong>EDIT:</strong></p>

<p>Of course <code>import bad.py</code> doesn't work. <code>import</code>-statements don't want any file-endings. I did this mistake because I also program in C. I changed the line to <code>import bad</code>. The output looks like this now:</p>

<pre><code>Hello Hello, World
</code></pre>