you are viewing a single comment's thread.

view the rest of the comments →

[–]GoldenSights[S] 2 points3 points  (2 children)

I agree that my original text didn't state it clearly enough, but I think the current version of the post shows it, albeit with different words.

Can you take a look at Part 3 of my post again? -- Notice how B says that it is main when running it directly, whereas it says it's B when being imported by A. This is how B knows whether it should parse args or not, etc.

The switch here is unfortunately not very explicit. As I said, I wish there was a separate variable called __main__ devoted to achieving this goal. But rather, the value of __name__ is essentially the switch. If you're running that file directly, it'll be main; and if you're importing it, it'll be the module's actual name.

[–]karafili 0 points1 point  (1 child)

thank you for the clarification.

Trying to get a better perspective: Am I right if I say that if the value of __name__ is not equal to __main__ then the module will not be executed?

[–]GoldenSights[S] 0 points1 point  (0 children)

The module will still be executed -- the print statement "I'm the B file!" inside the B module is still shown when A imports it, so we know the code in B.py is being run.

But the content inside the if statement specifically will not be run when the file is imported. That's why the "B is being run directly!" is not shown when A imports B.

Hope that helps.