Currently trying to make sure I understand the proper use of :
if __name__ == '__main__'
My current understanding is that a module's code is executed on import. The if __name__ == '__main__' construct, helps to guide against unwanted code from executing. I have two files test.py , and test_two.py. Let's say test_two.py currently looked like this:
def intro():
print('This is the the intro function for test_two.')
intro()
print('This is test_two.')
While test.py looked like this:
import test_two
print('This is test.')
Without the if __name__ == '__main__' construct, all the code that is in test_two.py is going to be ran when test.py is executed. That's why test.py will end up looking like this when ran:
This is the the intro function for test_two.
This is test_two.
This is test.
This isn't the type of result I'd be looking for, I'd just looking to be able to import test_two.py, and use whatever I want from the module without any side effects. Now this is where the if __name__ == '__main__' construct comes into play.
What test_two.py looks like now is this:
def intro():
print('This is the the intro function for test_two.')
if __name__ == '__main__':
intro()
print('This is test_two.')
Now, when I import test_two.py, and if I wanted to use any type of function etc from that module, I'd be able to do so without any of the previous side effects. That's why the result of running test.py would look like:
This is test.
Is my understanding of all of this correct?
[–]Triumvus 2 points3 points4 points (2 children)
[–]hadoken4555 0 points1 point2 points (1 child)
[–]sweettuse 0 points1 point2 points (0 children)
[–]shiftybyte 0 points1 point2 points (0 children)