What Happens When You Import a Module
00:13 And he will also mention tests a little bit. Although he won’t go into detail in this part, we will get to this in one of the next ones. For now, it’s mostly about what happens when you import a module.
00:28 So let’s make a new file in here. Call it—well, that can be the test file, right? I can write some tests for this as well. Yeah, you were mentioning tests when you were thinking of putting it into a function.
You were mentioning it would be easier to test, so that’s actually a good step. So now you’re creating a new file, and now you want to import the
double_characters() function from
double. Now we’re still showing about this
__main__, why it’s helpful.
you might expect that you get
"Tree" doubled printed out, and you will, but there’s also an additional thing. You can pause for a second and think about what’s going to happen. So if I run this, I get both Philipp’s name and then the input that I actually put in here printed out.
And if you import it, then it won’t because then it’s running in the namespace of the file. So the namespace is going to be
double, and here, the namespace is going to be
main if you run it directly. So I would move this
But at the same time, if I run the file directly, I get this
if that name is true, and then the indented code here executes. I mean, the point of this is just that you can still see some output from running the script directly, but it doesn’t interfere with the possibility for you to import the code somewhere else. Yeah, that was a really nice explanation in that regard that basically you would be using
__name__ == "__main__", and dunder is like a shorthand term for double underscore (
__), right here.
As you saw, the
if __name__ == "__main__" statement is really handy. The special variable
__name__ has the value
__name__ inside scripts, but it gets the name of the module inside imported modules.
Become a Member to join the conversation.