Sunday 17 December 2017

module - What does `if name == "__main__"` mean in Python?












I
have wrote scripts in Python for quite a while now and I study more of Python as I need
it. When reading other people's code I meet if name ==
"__main__":
construct quite often.



What is it good
for?



itemprop="text">
class="normal">Answer



This
allows you to use the same file both as a library (by importing it) or as the starting
point for an application.



For example, consider
the following file:



#
hello.py
def hello(to=__name__):
return "hello, %s" %
to

if __name__ == "__main__":

print
hello("world")


You can
use that code in two ways. For one, you can write a program that imports it. If you
import the library, __name__ will be the name of the library
and thus the check will fail, and the code will not execute (which is the desired
behavior):



#program.py
from
hello import hello # this won't cause anything to print
print
hello("world")



If
you don't want to write this second file, you can directly run your code from the
command line with something
like:



$ python
hello.py
hello,
__main__


This behavior
all depends on the special variable __name__ which python will
set based on whether the library is imported or run directly by the interpreter. If run
directly it will be set to __main__. If imported it will be set
to the library name (in this case, hello).



Often this construct is used to add unit tests
to your code. This way, when you write a library you can embed the testing code right in
the file without worrying that it will get executed when the library is used in the
normal way. When you want to test the library, you don't need any framework because you
can just run the library as if it were a
program.




See also href="http://docs.python.org/library/__main__.html">__main__
in the python documentation (though it's remarkably
sparse)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...