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! While you're at it, check out some resources Treehouse students have shared here.

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

Python Using Databases in Python Meet Peewee Modeling

Welby Obeng
Welby Obeng
20,340 Points

if __name__ == '__main__':

Can someone explain the if name == 'main':? What is if name and what is 'main'?

3 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

__name__ is the current namespace (Python has lots of 'em). When you run a script directly, the current namespace, instead of being the name of the file, is '__main__' because it's the main script running. So, if the current namespace is '__main__', because this file is being directly run, then do something special.

You can always print(__name__) in a script and see what the namespace is. Put that in a file that you import in another file and see what comes out.

Gavin Ralston
Gavin Ralston
28,770 Points

Every forum reply which answers this question moves us incrementally closer to having the following documentation removed from the official docs, the community awareness, and eventually hopefully every cache of every search engine everywhere, so it can never be found or used again:

It is this environment in which the idiomatic “conditional script” stanza causes a script to run:

It was removed in the 3.4 docs but someone still needs to send temporal agents back to strike it from every other version.

Camille Ferré
Camille Ferré
3,330 Points

Hello !

This thread is from a while ago, but any chance you could illustrate one example where we run the script directly and one where we would need to import ? It's still not so clear in my head.

Thanks a lot

not quite sure but what it does is check if you ran the program directly compared to importing it in a different file/library

That's correct - it checks whether the file was imported, or ran directly on the command line.

Welby Obeng
Welby Obeng
20,340 Points

I know that but I want the behind the scene why name will have main...maybe is the computer science in me haha