Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Using the Name-Main Idiom

In this lesson, you’ll fix the duplicated snakes. In the process, you’ll use the name-main idiom and remove the need to call python!

00:00 Now we get to show even one more thing that we should fix because now we’ve got two snakes. Yeah. What happened there? What did happen there? So now if we think about this, if we can go back to the source code for __main__, and the source code, and we can see that every time the file is loaded, it runs main(),

00:22 so that’s the first snake. And then as part of the snakey thing, we also say that we want to run the main(). Okay, so there’s something doing an importing process here, right?

00:34 It’s importing this file? Exactly. And whenever you import a Python file, it runs the file. So it’s going to run main(), but then it’s also going to say, “Oh, I need the main() function to call it,” so, and then it’s calling it again.

00:48 Okay. So that’s definitely not something we want. Right. So there’s a somewhat weird Python convention for how to fix this. And that’s something I guess we can call the name-main idiom, and it spells out the __name__ and checks whether that’s equal to "__main__". And there should be some equals somewhere in your code there. Oh,

01:12 yes. So this __name__ is a special variable that just gets a name from the file it’s running, so to speak. And with this, now we should only see one snake. Right, and since it’s an editable install, we don’t need to reinstall anything because we haven’t changed anything in the pyproject.toml. We’ve just changed stuff in the source code. Yep.

01:32 And now we can call snakey hello from anywhere, and now it works perfectly, and I can go anywhere I like and have access to this snakey command. Exactly.

01:42 Yeah. So now you have really created a tool that you can use wherever you are on your computer, as long as it’s in your environment. Fantastic. It’s beautiful.

01:51 It is beautiful because we only need one file now, as well, and everything seems to just work.

Become a Member to join the conversation.