__name__ is a built-in variable name which will be __main__, if the file is executed directly. If the file is a module being imported in another file, the __name__ will become the file name.
Let’s create two file, file1.py and file2.py
In file1.py
print(f'my name is {__name__}')
In file2.py
import file1
If enter ‘python file1.py’. It will output
my name is __main__
If enter ‘python file2.py’. It will output
my name is file1
Now we add if else statement inside both file1.py and file2.py
In file1.py, we add
if __name__ == "__main__":
print('file 1 is executed directly')
else:
print('file 1 is being imported')
In file2.py, we add
if __name__ == "__main__":
print('file 2 is executed directly')
else:
print('file 2 is being imported')