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 Basic Object-Oriented Python Creating a Memory Game Card Class

I'm not sure I wholly understand the if __name__ == '__main__': part of the code. What is it doing, precisely?

As I stated, the if name == 'main': part of the code confuses me. I understand practically that it's making it so that it returns True if the two words are equal, but I don't understand how.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Hey Eric Nachtsheim, good question!

During any python module execution, the value of __name__ is set to the name of the current .py module name. This is true for any imported module. The one exception to this is in the top level module name where __name__ is set to __main__ This allows for the if condition you mention to be used to allow execution of code if and only if the current module was the top most module invoke from the OS command line.

Post back if you need more help. Good luck!!!

Andrew Leibowitz
Andrew Leibowitz
2,529 Points

What does it mean if the current module is the top most module invoke from the Os command line? Sorry I'm a little confused.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Hey Andrew Leibowitz, when running Python code, each module run has the __name__ attribute set to the name of the module. The exception is the module referenced on the command line. It’s __name__ attribute is set to ”__main__” to identify it as the top module involved by python interpreter.

$ python some_module.py

While running some_module, it is treated as the top most module. Any other module imported modules would be beneath it.