9) b. Main Function

Take a look at this example and try to guess the output.

1
2
3
4
5
6
7
# my_lib.py

def high_level_math_equation():
    return 2 * 2

# Test a function in a modules body.
print(high_level_math_equation())
1
2
3
4
5
6
# my_script.py

import my_lib

print("Solving the equation...")
print(my_lib.high_level_math_equation())
1
2
3
4
Output:
4
Solving the equation...
4

Can you guess why 4 was printed twice?



When a module is imported it is first executed fully to make sure that all of its members are created. So if you left some code that is executed directly in module’s body, it will be run every time you import it which depending on your situation may not be what you want.

But what if you still want to have some code that is executed when calling the module directly and not when it is imported?

Every module has a built-in variable called __name__ which contains the name of the module. Interestingly, the value of __name__ which is executed directly is not its name but a string __main__.

1
2
Output:
__main__



The python module that you run directly will always know itself as “__main__”.

However, an imported module will know itself by its original file name. Here is what this means:

1
2
3
4
5
# my_script.py

import my_lib

print(__name__)
1
2
3
Output:
my_lib
__main__




Here is a representation of what is happening.



You can use this property to change your my_lib.py file to the following.

1
2
3
4
5
6
7
8
# my_lib.py

def high_level_math_equation():
    return 2 * 2

if __name__ == "__main__":
    print("This will only be printed if this file is run directly.")
    print(high_level_math_equation())