[PYTHON] Briefly about __name__

name

In the code you are running, __ name __ ='__main __' Inside the imported file, __ name __ ='filename' is included By distinguishing this, you can see which file is running Therefore, you can create a mechanism that main () is not executed when the main file is called by another file.

Concrete example

b If the file does not have if name =='main':

b.py


def import_print_name():
  return __name__

print(import_print_name())

main.py


import b

def main():
  print("It will be the imported file name. In this case",b.import_print_name())
  print(__name__)

if __name__ == '__main__':
  main()

Execution result (execute main).


b
It will be the imported file name. In this case b
__main__

The above b is called at the time of import b

b If the file has if name =='main':

b.py


def import_print_name():
  return __name__

if __name__=='__main__':
  print(import_print_name())

main.py


import b

def main():
  print("It will be the imported file name. In this case",b.import_print_name())
  print(__name__)

if __name__ == '__main__':
  main()

Execution result (execute main).


It will be the imported file name. In this case b
__main__

Recommended Posts

Briefly about __name__
__name__
[Python] Let's write briefly about comprehensions
About LangID
About CAGR
About virtiofs
About python-apt
About Permission
About sklearn.preprocessing.Imputer
About gunicorn
About requirements.txt
About locale
About permissions
About Opencv ②
About axis = 0, axis = 1
About Opencv ③
About import
About numpy
About pip
About Linux
About numpy.newaxis
About endian
About Linux
About import
About Opencv ①
About Linux
About Linux
About Linux ①
About cv2.imread
About _ and __
About wxPython