if __name__

2023-05-12 python __main__ boilerplate

As I am learning more python, I run across common pattern in sample code. It looks like this and it is very common

def main():
    print("Let's go")

if __name__ == "__main__":
    main()

looking for sources on internet I found this article. It is quite simple, the idiom allows to have script that can be imported without running the main function, but run it when started as a script. In essence this is very similar to Modulino concept I already saw in perl world.

More description can be found in official documentation. In short, the __name__ contains current environment. Top level scripts or modules called -m have special string __main__ in the variable, otherwise there is name of current module.

Quick demonstration, let’s have a module blem

print(f"Module: {__name__}")

and a script loading it

import blem
print(f"Script: {__name__}")

This outputs

Module: blem
Script: __main__