September 8, 2025
The main function in Python is declared, like this: def main(some parameter):
The if __name__ == "__main__"
guard checks whether a Python file has a main function.
Direct run: then __name__
is set to "__main__"
-> block inside will be run.
Imported Python File e.g.: import my_script
then __name__
is set to my_script
-> no need for main
function.
Let’s see some other programming languages:
In Python, you don’t always need a main()
function like in C, C++, or Java.
main()
Python does not require main
function
main
function is an entry point in some languages: C, C++, Rust, Java
NOTE: C++ header files are not behaving the same as import python_code
!
Function main
behaves like other functions in Python
Therefore it is harder to detect main function in Python programs
#include <iostream>
#include <vector>
std::vector<int> vec(std::vector<int> vec_int) {
if (sizeof(vec_int) == 0) {
std::cout << "Vector could not been found!";
}
for(int i: vec_int) {
std::cout << i;
}
if(sizeof(vec_int) != 0) {
return vec_int;
}
}
std::vector<int> ints = {1,2,3,4,5,6,7,8,9,10};
vec(ints); // NOTE: Here we get a compiler error!
int main() {
std::cout << "Only functions in main get executed in C++ or if they get called in a function that is executed in the main function!";
}
main
function in Python.main
function like other languages.Proofgrammers