[Supplementary course] If __name__ == If you write the code under'__main__', raise your hand.

Hello everyone. If \ _ \ _ name \ _ \ _ =='\ _ \ _ main \ _ \ _', who writes the code lazily, raise your hand Has exceeded 100 likes, thank you. Teacher, I have something to tell everyone.

The horror of Shadows name

Everyone, I overlook the Shadows name warning. Explain the horror of Shadows name caused by polluting the global scope.

Sorry for the tricky example, but suppose you have the following code:

import sys

def process(n):
    x = 0

    # ...Various processing

    if x > 1:
        n *= 10

    # ...Various processing

    return n


if __name__ == '__main__':
    for x in sys.argv[1:] or [1, 2, 3]:
        process(int(x))

For some reason, I no longer need to start the process function, so I commented out the variable x. However, I overlooked the variable x that was buried in the code in the middle.

def process(n):
    #Comment out here
    # x = 0

    # ...Various processing

    # !!!!I forgot to comment out!!!!
    if x > 1:
        n *= 10

    # ...Various processing

    return n

In this case, x is referenced as a global variable, so no error occurs and it is not detected by static analysis tools.

Simple mistakes in Python can be detected by 99% static analysis, but Shadows name is a nasty bug that slips through it. By bypassing static analysis, you need to pay close attention to even one comment out.

** So don't dissipate the Python teacher's language specs. ** **

Of course, the previous example was an extreme situation, but it's quite possible. If you run the risk of causing such a nasty bug, it's easier to wrap the function under ʻif name =='main'` as soon as possible.