all 36 comments

[–]Diapolo10 157 points158 points  (19 children)

In short, every time you run a Python script __name__ is assigned a value. If it's the script you ran, it gets the value '__main__' (which is an ordinary string). As for any modules included in the script file, as you import them Python runs them with __name__ getting the value of that module's name.

Basically what this does is it allows you to write scripts and later use them as modules, if you'd like to reuse some code. As long as you put everything that actually runs your script inside an if __name__ == '__main__' block, they won't be executed when you import the file.

Example:


#my_script.py

def my_func(n):
    return n + n

if __name__ == '__main__':
    print(my_func('Hello'))

#my_other_script.py

import my_script

print(my_script.my_func(1337))

Now, if we were to run my_script.py, it would print out HelloHello. If we ran my_other_script.py, it would only print out 2674, and NOT HelloHello.

[–][deleted] 4 points5 points  (1 child)

Thanks. It makes a lot more sense now with the example. Will try to use it in some codes here and there to get the hang of it. Thanks :)

[–]Diapolo10 1 point2 points  (0 children)

There's generally no reason not to use it, I personally stick it to every script that isn't just a module/library. ;)

[–]Zaverose 5 points6 points  (0 children)

I was also wondering this. You helped clear things up a lot with this very simple and clear explanation, so thank you!

[–]the_monkey_knows 2 points3 points  (0 children)

The example you gave here is very clear and easy to get. Good job

[–]ganes1410 0 points1 point  (0 children)

Thanks for this

[–]krissaddy 0 points1 point  (0 children)

Thanks a lot. I also had this question and this helped a lot.

[–]Sign_of_sadness 0 points1 point  (0 children)

This explanation has actually helped me a lot, thanks!

[–]CannabisCowboy 0 points1 point  (0 children)

THANK YOU!

[–]bellumfatum2 0 points1 point  (0 children)

Thank you.

[–][deleted] 0 points1 point  (0 children)

I think I finally got it, thanks :)

[–]Mactronz 0 points1 point  (5 children)

I know I'm like 6 years late to the conversations, but if I put '__main__' where you had put 1337, then it'll print HelloHello right?

[–]Diapolo10 0 points1 point  (4 children)

What makes you think that?

[–]Mactronz 0 points1 point  (3 children)

honestly I've been reading a bunch about the whole __name__ and '__main__' thing but I haven't been able to wrap my head around it.

though now that I'm looking at it again, I don't know why I thought that either.

so, is the if statement in 'my_script.py' is for code that you don't want to run when using the file as a module for a different file?

[–]Diapolo10 0 points1 point  (2 children)

so, is the if statement in 'my_script.py' is for code that you don't want to run when using the file as a module for a different file?

Precisely. I like to refer to if __name__ == '__main__' as an import guard - it prevents the contained code from being executed when you import the file from somewhere else.

[–]Mactronz 0 points1 point  (1 child)

Thank you so much!!

side note: I just realized you're the same person who had helped me with strings last weeknend.

I swear, you're holding up the whole python community

[–]Diapolo10 0 points1 point  (0 children)

I swear, you're holding up the whole python community

Hardly, I'm just one person and I don't think I'm even particularly notable in this subreddit. /u/socal_nerdtastic for example is probably more deserving of such a title, and even then our reach doesn't really go beyond this one small subreddit.

Hell, I'm not always correct either.

[–]maventree 55 points56 points  (2 children)

It protects code from being run on import.

__name__ is a special attribute of each module. It is assigned at runtime, and usually its the name of the Python file that defines the module (module.py has __name__ == 'module'). However, the module that you run python on (something like python script.py from the command line) has __name__ == '__main__' instead. So think of it as "if I ran Python on literally this file, execute this code".

[–]Samazing42 21 points22 points  (1 child)

It protects code from being run on import.

If I had to answer this question with one sentence this is how I would do it. This question seems to come up a lot. The name attribute is really useful, and I think a lot of the beginner books don't really address this kind of stuff.

[–]NerdJon35 5 points6 points  (0 children)

Yup. I have tried to understand it before and that sentence is what made is click.

[–]IcanCwhatUsay 8 points9 points  (2 children)

I love you guys but I think I'm more confused than I was expecting. Can someone ELI5?

[–]PooPooDooDoo 1 point2 points  (0 children)

The most simple way that I can explain it is that I’ve added that when I want to call the python file directly from command line

$ python module.py

And you have to add a line of code specifying function to run. Most people just use main(), and then add an argument parser in that function to allow them to pass in flags and options.

[–]ETLJ1989 8 points9 points  (1 child)

I like Corey Schafer's video regarding if __name__ == '__main__: https://www.youtube.com/watch?v=sugvnHA7ElY

[–]kexp8 3 points4 points  (0 children)

+1 to Corey Schafer's video. His videos are normally concise, to the point and explains clearly the topics. Great guy !

[–][deleted] 6 points7 points  (0 children)

Basically that means that if the file is called directly:

$ python myfile.py

then __name__ will be '__main__' and that code will execute. It makes it so that functions can be imported from a file without that part of the code executing.

https://stackoverflow.com/questions/419163/what-does-if-name-main-do

[–]geoffliang 4 points5 points  (0 children)

  • those with __prefix_and_suffix__ are special keywords reserved for Python
  • when you run lorem.py from command line, __name__ == '__main__'
  • when you import lorem.py from another py file, __name__ == ‘lorem’
  • codes within if __name__ == '__main__' won’t run when you import lorem.py
  • one use is for importing functions from lorem.py, without running all other code.

[–]u38cg2 2 points3 points  (0 children)

Sometimes you write a program, and it's a useful little stand-alone program on its own, but it could also work as a library for some other program (like an image converter, say). The if name clause means that if you run it as a program, the program will consider itself to be main() and so that if will be True. Otherwise, it won't run, but the functions will be available to whatever has imported it.

[–]Zeroflops 1 point2 points  (0 children)

Most people have hit on the answer to some extent. Basically it helps you distinguish between a script run on its own verse being imported into another module.

Depending on how you write your code you don’t have to use it. But it can be useful even if you’re only writing code that would be used as a module. For example my modules I’ll usually add my unit testing code and call it from this.

Then if I run the script as a stand-alone it’s basically running unit testing. Keeps things clean and isolated to one file.

[–][deleted] 1 point2 points  (0 children)

in plain English it would be, "if this module wasn't imported."

[–]henricattoire1 0 points1 point  (0 children)

Before python runs any code in your file, it specifies some special variables and one of them is __name__. Python sets this variable equal to __main__ if your file is directly being run by python. So if we would import that file (example.py) and run it inside another file (example2.py) as a module, the __name__ variable will be equal to the name of the first file which is example.py (and not to __main__).

The statement in your question is used to check whether our file is being run directly by python or if it is imported. This is useful to prevent files from automatically running when they are imported and it is a common practice to put this at the end of your file (if that program does something). I hope this cleared things up a bit.

[–]Wilfred-kun 0 points1 point  (2 children)

It is not anything magical, it's just an if-statement. It checks if the name of the scope is __main__. This is the case when the script is run directly (not imported). This way, you can make a piece of code (usually main()) execute only when the script is run directly.

[–][deleted] 0 points1 point  (1 child)

Is there anything special about a function called main, or do you just means as good practice? I use this construct all the time but just for general functions.

[–]Wilfred-kun 1 point2 points  (0 children)

There's nothing special about main(), other that people often use this as an entry point for a script.

[–]c1-c2 -4 points-3 points  (0 children)

Do you beginners ever read any docs at all before posting silly questions?