3

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__?

drum
  • 5,416
  • 7
  • 57
  • 91
  • 4
    Possible duplicate of [What does if \_\_name\_\_ == "\_\_main\_\_" do?](http://stackoverflow.com/questions/419163/what-does-if-name-main-do). I realize that you mentioned your knowledge of that particular use, but the accepted answer does give you the answer you seek. – zondo Apr 30 '16 at 00:16
  • 4
    `logger = logging.getLogger(__name__)` – Colonel Thirty Two Apr 30 '16 at 00:19
  • I don't see the answer that I want. – drum Apr 30 '16 at 00:20

1 Answers1

10

__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
chepner
  • 497,756
  • 71
  • 530
  • 681
T. Arboreus
  • 1,067
  • 1
  • 9
  • 17
  • 1
    Is there any other usage other than knowing the module's name? – drum Apr 30 '16 at 01:51
  • The "if __name__ = '__main__' idiom allows you to create different behaviors based on whether a script is called directly or as a module. That's the most common use case. It might potentially have some use in debugging or reporting in unit tests. – T. Arboreus Apr 30 '16 at 02:50