Basic cheatsheet for Python mostly based on the book written by Al Sweigart, Automate the Boring Stuff with Python under the Creative Commons license and many other sources.
__main__
Top-level script environment¶__main__
is the name of the scope in which top-level code executes.
A module’s name is set equal to __main__
when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__
, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m
but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
For a package, the same effect can be achieved by including a main.py module, the contents of which will be executed when the module is run with -m.
For example we are developing script which is designed to be used as module, we should do:
# Python program to execute function directly
def add(a, b):
return a+b
add(10, 20) # we can test it by calling the function save it as calculate.py
# Now if we want to use that module by importing we have to comment out our call,
# Instead we can write like this in calculate.py
if __name__ == "__main__":
add(3, 5)
import calculate
calculate.add(3, 5)
__name__
defined and if this is __main__
, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.__name__ == “main”:
is used to execute some code only if the file was run directly, and not imported.