Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


if __name__ == '__main__':

I'm not sure I understand how exactly this statement functions. What object's name attribute are we checking against? And how does having this condition help us only run the code in the command line, but not if we import it somewhere else? Any sort of clarification would be helpful, thanks!

1 Answer

Nathan Tallack
Nathan Tallack
22,159 Points

When Python is interpreting your code, it has an internal variable called __name__ which will reveal the "namespace" that your code is being run from. This is so you can have it do one thing if called directly, or do another if imported by some other code with an import statement.

You can use this to identify if your code is being called directly, for example if you launch it from the CLI command line as with the python mycode.py command. In this case the variable __name__ will return the string '__main__'.

The reason you want this is so that you can perhaps call a function to start your code running. For example, if your code is designed to be run directly (as a game perhaps) this could call a function or class method to start your game.

But let's say your code is designed to be used by other code. Perhaps your game is designed so that it can be used as an API library allowing you to reference the leaderboard statistics of your game play. So then your website backend code might import one or more functions from your game and use that to show that leaderboard code. In this case your code won't start your game up when it is imported because __name__ will not equal '__main__' but will equal the namespace that you are importing into.

Long winded, but I am as new to this as you so I am not good enough to explain it better than that. Perhaps some uber python peoples can give you a better answer. :)