DEV Community

Cover image for Does Python has a main function?
Manitej ⚡
Manitej ⚡

Posted on • Originally published at manitej.hashnode.dev

Does Python has a main function?

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__)
Enter fullscreen mode Exit fullscreen mode

This code outputs,

__main__
Enter fullscreen mode Exit fullscreen mode

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__)
Enter fullscreen mode Exit fullscreen mode

I imported file1 here and printed the __name__
Now, the above code outputs,

file1
Enter fullscreen mode Exit fullscreen mode

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()

Enter fullscreen mode Exit fullscreen mode

There's no actual reason to use this above process. Its just a feature :)

Top comments (7)

Collapse
 
alekseiberezkin profile image
Aleksei Berezkin

It doesn't have main function but it does have main if instead 🙂

Collapse
 
whiteheadbanger profile image
Sebastian

Explained really well!

Collapse
 
manitej profile image
Manitej ⚡

Thanks!

Collapse
 
manitej profile image
Manitej ⚡

Exactly, I never used it anywhere personally.

Collapse
 
titanhero profile image
Lex

😁✌️👍

Collapse
 
manitej profile image
Manitej ⚡

Thanks!

Collapse
 
manitej profile image
Manitej ⚡

If you are hiring let me know 😁