First of all I have to say, that I'm not new in Python. I know the use of if __name__ == '__main__': well enough. I just try to understand how 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 possibilities.
main.py:
import bad.py
def main():
print "Hello, World!"
if __name__ == '__main__':
main()
bad.py:
__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()
There's no output by running main.py and I didn't really expect an output.
what I want to know:
- does
__name__ = '__main__'inbad.pyautomatically change the variable__name__inmain.py? Or can two different'__main__'-modules exist? - is it possible to substitute an
importstatement just by manipulating__name__? If it is, how would you do that? when I change
exit()toprint "Hello",, The output is"Hello", then an Error occurs:Traceback (most recent call last): File "main.py", line 1, in <module> import bad.py ImportError: No module named pycould someone explain this behaviour?
- Are there any differences between python versions / operating systems? I tried this example in Python 2.7.6 on Linux2
EDIT:
Of course import bad.py doesn't work. import-statements don't want any file-endings. I did this mistake because I also program in C. I changed the line to import bad. The output looks like this now:
Hello Hello, World