What is the main method?
If you're familiar with languages like C
, C++
etc you may have noticed the fact that we must need to use the main()
method in your code. As those languages use the compiler(compiles all code at once) to run the code, it needs an entry point to start the compilation. But Python uses an interpreter(compiles code line by line), which means it doesn't need an entry point it'll simply start compilation from line 1. So, Python doesn't have a main function . But it has a concept called main modules
.
The __name__
variable in Python
The __name__
is a special predefined variable in Python which stores the name of the current module.
Example
Consider the following code in a file file1.py
,
# file1.py
print(__name__)
This code outputs,
__main__
Python by default stores the value of __name__
variable as __main__
(which indicates that this is the main module )
Now, consider the below code in a file file2.py
,
# file2.py
import file1
print(__name__)
I imported file1
here and printed the __name__
Now, the above code outputs,
file1
What's the point here?
As you saw above, file1.py
doesn't have any imported code. That's why the __name__
variable has a value of __main__
which means it is the main module
but in file2.py
we have imported the file1.py
into file2.py
. Then the interpreter changes the __name__
variable to the imported module name in our case its file1
.
if the module doesn't have any imports, then it will be the main module.
Now if you want to do certain things only in the main module
not in the imported code, you can do like below.
def show ():
print("Hello world")
# Only call the show method in main module
if __name__ == "__main__" :
show()
There's no actual reason to use this above process. Its just a feature :)