Python statement I hated the most🤯

if name == “main

When I started with Python, I just didn’t get why would such an ugly looking line of code be there always??

But it did make sense when I started to work in IDEs with multiple files.

When we work with multiple files having different classes and functions, there is a need to use them in other files as well.

If some functions defined in file A have to be implemented in B, we simply import the file A in B.

But, if the file A doesn’t contain the main statement, all the code written in the file A will get executed before the code in file B starts to execute.

To keep this mess from happening, we need to include the above main statement, which is similar to the main function in C/C++.

But what is this name ?

It is a special variable in Python. When you are in file A, Python sets name as main.

However, when you import the file A and run its function in B, the name will then be ‘A’. As that is a function of file A and not one of the main functions of file B.

So, when Python realizes that now name is not equal to main, it won’t go into the if statement and the code there won’t be executed.

Note that if you check the name explicitly in file B, it will still be main for that file.

#python #datascience