What is the role of 'if __name__ == '_main__'?

Asked 2 years ago, Updated 2 years ago, 144 views

What is the role of if__name__=="__main_":?

# Threading example
import time, thread

def myfunction(string, sleeptime, lock, *args):
    while 1:
        lock.acquire()
        time.sleep(sleeptime)
        lock.release()
        time.sleep(sleeptime)
if __name__ == "__main__":
    lock = thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

main module idioms python namespaces

2022-09-21 22:04

1 Answers

The Python interpreter reads the source file and executes all the code in that file. Before executing the code, the interpreter defines several special variables, for example, if the module (source file) the interpreter wants to execute is executed as the main program, the interpreter specifies a special variable called _name__ as _main_". Conversely, if the module is called by another module, __name__ is named for that module.

Take the code you posted, for example, and think of it as running as the main program.

python threading_example.py

In other words, if you use the command line to execute the above, the interpreter will set all the special variables and then execute the import statement to load the appropriate modules. The def block is then read to create a function object and a variable called myfunction that points to that function object. Next, read the if statement, verify that _name__ matches "_main_", and execute the internal code.

The reason for this type of verification is that the Python module you created (the .py file) is sometimes written to run directly. Conversely, it can be called and used by other modules. By checking if the module is the main program, you can run the same module as a single program as needed, or you can recall functions inside the module by recalling the module from another module.

More specific information can be found on this page.


2022-09-21 22:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.