-2

Good time of day. I would like to know about __main__ and __name__. Let's say I have a main file and a second file. If I import a function from the main file into the second one, and run the second file, does it stop being __main__?

I tried to run the main file after I imported the function from it, and in it __main__ == __name__ could you explain to me why this is happening? And one more question, did I understand correctly that it is not worth importing anything from the main file?

matszwecja
  • 6,357
  • 2
  • 10
  • 17
Treeesk
  • 11
  • 4
  • It's `"__main__"`, not `__main__` (note the `"`). It's an important difference as `__main__` is undefined variable and will raise an error. – matszwecja Jul 06 '23 at 07:46

1 Answers1

0

If you are importing from another file, __name__ would be the file's name (not '__main__).

The steps are:

  1. run a python file
  2. the file imports a function which contains a __name__== '__main__' construction from function_file.py as from fuction_file import func
  3. you get the following output:

function_file.py

def func():
    print('Function call from another file')
    if __name__ == '__main__':
        print(f"""Entered `__name__ == '__main__'` block""")
    else:
        print(f"""Could not enter `__name__ != '__main__'` block""")
        print(f"""__name__ = '{__name__}'""")

Output:

>>> Function call from another file
>>> Could not enter `__name__ != '__main__'` block
>>> __name__ = 'function_file'
Ivan
  • 1
  • 1