Speak now
Please Wait Image Converting Into Text...
Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Challenge yourself and boost your learning! Start the quiz now to earn credits.
Unlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
General Tech QA/Testing 2 years ago
Posted on 16 Aug 2022, this text provides information on QA/Testing related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.
Turn Your Knowledge into Earnings.
What does the if __name__ == "__main__": do?
if __name__ == "__main__":
# Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while True: 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))
Whenever the Python interpreter reads a source file, it does two things:
it sets a few special variables like __name__, and then
__name__
it executes all of the code found in the file.
Let's see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.
Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.
foo.py
# Suppose this is foo.py. print("before import") import math print("before functionA") def functionA(): print("Function A") print("before functionB") def functionB(): print("Function B {}".format(math.sqrt(100))) print("before __name__ guard") if __name__ == '__main__': functionA() functionB() print("after __name__ guard")
When the Python interpeter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.
When Your Module Is the Main Program
If you are running your module (the source file) as the main program, e.g.
python foo.py
the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.
"__main__"
# It's as if the interpreter inserts this at the top # of your module when run as the main program. __name__ = "__main__"
When Your Module Is Imported By Another
On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:
# Suppose this is in some other main program. import foo
In this case, the interpreter will look at the filename of your module, foo.py, strip off the .py, and assign that string to your module's __name__ variable, i.e.
.py
# It's as if the interpreter inserts this at the top # of your module when it's imported from another module. __name__ = "foo"
After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.
Always
It prints the string "before import" (without quotes).
"before import"
It loads the math module and assigns it to a variable called math. This is equivalent to replacing import math with the following (note that __import__ is a low-level function in Python that takes a string and triggers the actual import):
math
import math
__import__
# Find and load a module given its string name, "math", # then assign it to a local variable called math. math = __import__("math")
It prints the string "before functionA".
"before functionA"
It executes the def block, creating a function object, then assigning that function object to a variable called functionA.
def
functionA
It prints the string "before functionB".
"before functionB"
It executes the second def block, creating another function object, then assigning it to a variable called functionB.
functionB
It prints the string "before __name__ guard".
"before __name__ guard"
Only When Your Module Is the Main Program
"Function A"
"Function B 10.0"
Only When Your Module Is Imported by Another
"foo"
if
"after __name__ guard"
Summary
In summary, here's what'd be printed in the two cases:
# What gets printed if foo is the main program before import before functionA before functionB before __name__ guard Function A Function B 10.0 after __name__ guard
# What gets printed if foo is imported as a regular module before import before functionA before functionB before __name__ guard after __name__ guard
You might naturally wonder why anybody would want this. Well, sometimes you want to write a .pyfile that can be both used by other programs and modules as a module and can be run as the main program. Examples:
Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.
Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.
No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.
General Tech 10 Answers
General Tech 7 Answers
General Tech 3 Answers
General Tech 9 Answers
General Tech 2 Answers
Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.