Python: if __name__ == “__main__”



If you have been programming in Python for a bit it is probable you came across the code if __name__ == “__main__” and that you, like me and many others before, had no clue of what it means. Below a short explanation of how I understood it. Hope it helps!

The main function is essentially where any Python program starts. The Python interpreter (= program, which reads and executes code) sequentially reads the source file (= module) and executes the code.

Remember, the main function can only be processed if the interpreter reads it as a Python program! Otherwise, it is ignored.

This is why the following code will not return anything:

def main():
    print(2+2)

It is seen as a module and hence skipped! Essentially, the function is just defined, and not yet called.

Solutions:

In Python 3 (or later) an easy solution would be to easily call the main function at the end of the code for the function:

def main():
    print(2+2)
main()

This calls the main function and executes the code.

Another solution is to call the code in the main function we want to run if the “special” variable (see below) __name__ is equal to “__main__”:

def main():
    print(2+2)if __name__ == “__main__”:
    main()

Why does this work? Before executing code, the Python interpreter reads the source file and defines a few “special” variables. The variable __name__ is one of these and evaluates the name of the current module.

If the Python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. The if statement allows checking whether a function is run from the current script or if it has been imported from another one.

If it is imported from another module, __name__, will be set to that script’s name!


Source: Paper.li

Recent Posts

See All

Build simple fuzzer - part 1

First of all, we are learning here and this fuzzer is in no way going to be a proper tool used against real targets (at least not initially). This is why we are going to code it in python. For real to

Build simple fuzzer - part 2

In the previous part of this mini-series we’ve implemented a very simple fuzzer. As the main idea behind it is being an exercise therefore I don’t think it is capable of finding bugs in complex target