Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Questions about __name__
I was wondering why instead of just starting up the main function, if __name__ == '__main__' is used before starting the main function? Also, what decides what __name__ is equal to? It is usually '__main__', but in what cases is it not? Thanks in advance!
bhojendra likes this post
Age Doesn't Matter, Your Passion Does
- Shreya Jain
This line is used to distinguish execution behavior when the file is imported as a module, or is executed as a script. When it is executed as a script builtin variable __name__ is set to __main__, when the file is imported as a module __name__ is set to filename.

Let we have with that construction. When you call this file e.g. python the code under if-statement will be executed. If you import the file as a module, e.g. put somewhere import myfile, the code under if-statement wouldn't be executed.
I understand now. Thank you!
Age Doesn't Matter, Your Passion Does
- Shreya Jain
if __name__ == '__main__':
    print('Run by interpreter')
    print('Module was imported')
andre@andre-GP70-2PE:~$ python Run by interpreter andre@andre-GP70-2PE:~$ ipython Python 3.7.3 (default, Apr 15 2019, 14:17:18) Type 'copyright', 'credits' or 'license' for more information IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import test_main Module was imported In [2]:
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die:
All humans together. We don't need politicians!

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Discord bot that asks questions and based on response answers or asks more questions absinthium 1 3,276 Nov-25-2017, 06:21 AM
Last Post: heiner55

Forum Jump:

Users browsing this thread: 1 Guest(s)