Skip to content

Instantly share code, notes, and snippets.

@vitalizzare
Last active May 28, 2021 07:20
Show Gist options
  • Select an option

  • Save vitalizzare/ec2895b7c47f89e72d51fefb718e3e2c to your computer and use it in GitHub Desktop.

Select an option

Save vitalizzare/ec2895b7c47f89e72d51fefb718e3e2c to your computer and use it in GitHub Desktop.
What does it mean in python: if __name__ == "__main__"
# In the programm my_app.py we only import
# the module "test.py" from the folder "modules"
import modules.test
# Create a folder with name "modules" and put this file there, then run separately
# python my_app.py
# python modules/test.py
# and compare the output.
#
# REFERENCES:
# https://docs.python.org/3/library/__main__.html?highlight=__name__
# https://docs.python.org/3/reference/import.html?highlight=__name__#__name__
print('PART 1\n'
'This code will be executed in any case.\n')
if __name__ == '__main__':
print('PART 2\n'
'The code will be executed only if we run the file as a separate program. '
'In this case a built-in variable\n__name__ =', __name__, '\n')
else:
print('PART 3\n'
'This part will be executed only when we import the file as a module in other program. '
'In this case the built-in variable __name__ will be assigned to the name of the file '
'as we specify it with the import statement. In my case I named the file as "test.py" '
'and put it in a folder "mudeles", then imported in "my_app.py". Therefore:\n'
'__name__ =', __name__, '\n')
@vitalizzare
Copy link
Author

vitalizzare commented May 26, 2021

About "main"
About name

    git clone https://gist.github.com/ec2895b7c47f89e72d51fefb718e3e2c.git
    cd ec2895b7c47f89e72d51fefb718e3e2c/
    mkdir modules
    mv test.py modules/
    python my_app.py
    python modules/test.py

    $ tree 
    .
    ├── modules
    │   └── test.py
    └── my_app.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment