Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of __name__?

Tags:

python

What does __name__ do? I have only seen it paired with __main__ and nothing else.

I know that the classic if __name__ == __main__: defines the behavior when acting as a package vs running as stand-alone.

However what other usages are there for __name__?

like image 340
drum Avatar asked Oct 18 '25 01:10

drum


1 Answers

__name__ is "__main__" if you're executing the script directly. If you're importing a module, __name__ is the name of the module.

foo.py:

print(__name__)

bar.py

import foo

Run the scripts:

$ python foo.py
__main__
$ python bar.py 
foo
like image 192
T. Arboreus Avatar answered Oct 20 '25 14:10

T. Arboreus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!