Questions about __name__ - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Questions about __name__ (/thread-19700.html) |
Questions about __name__ - SheeppOSU - Jul-11-2019 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!
RE: Questions about __name__ - scidam - Jul-11-2019 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 myfile.py with that construction. When you call this file e.g. python myfile.py 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.
RE: Questions about __name__ - SheeppOSU - Jul-11-2019 I understand now. Thank you! RE: Questions about __name__ - DeaD_EyE - Jul-11-2019 if __name__ == '__main__': print('Run by interpreter') else: print('Module was imported')
|