Home python What does if __name__ == “__main__” do?

What does if __name__ == “__main__” do?

Author

Date

Category

What happens when you call 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))

Translation of the question “What does if __name__ ==“ __main__ ”do? @Devoted .


Answer 1, authority 100%

When the Python interpreter reads a source file, it executes any code it finds in it. Before starting to execute commands, it defines several special variables. For example, if the interpreter runs some module (source file) as the main program, it assigns the special variable __name__ to "__main__" . If this file is imported from another module, the variable __name__ will be assigned the name of this module.

In the case of your script, suppose the code is executed as the main function, for example:

python threading_example.py

After setting the custom variables, the interpreter will execute the import statement and load the specified modules. It will then parse the def block, create a function object and a variable named myfunction to point to that object.

It will then read the if statement, “understand” that __name__ is equivalent to "__main__" , and execute the specified block.

One reason to do this is because sometimes you write a module (file with the extension .py ) to be executed directly. Moreover, it can also be imported and used from another module. By performing such a check, you can make the code execute only if the given module is running as a program, and prohibit execution if you want to import it and use the module functions separately.

For more information see this page .

What does “threading_example currently import from another module” mean?

This means that someone in a .py file (or during an interactive Python session) is using the expression import threading_example . The opposite is the case – the user uses the expression python threading_example.py or ./threading_example.py , etc. In the latter case, threading_example.py launched as main program. In the first case, it is started somehow differently (to understand, look for a call like import threading_example ).

Translation of the answer “What does if __name__ ==“ __main__ ”do? @Mr Fooz .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions