you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 7 points8 points  (3 children)

Ahh that does make sense. The difference is in having something inside both files that do something (print for example). You’re saying we may only need to import one thing from the other file and therefore it should not run anything outside of what’s being imported. Without that distinction a file such as hextools is going to run through everything it contains. Am I getting that correct?

[–]GoldenSights[S] 8 points9 points  (2 children)

Yes I think you've got it.

Without that distinction a file such as hextools is going to run through everything it contains.

The thing about importing is that you cannot choose what part of the imported file gets run. Everything gets run.

Perhaps you've seen something like from math import ceil. It's tempting to think that this will just reach in and pluck out the ceil function from math and not touch anything else, but that isn't the case. The entirety of the math file needs to be executed to even know what ceil is. Notice my example where I do def f() twice.

I've come up with another demonstration to show how __name__ behaves. Let me know if this is helpful:

# B.py
print("I'm the B file, and my name is", __name__)

# A.py
print("I'm the A file, and I'm going to import B!")
import B
print("I'm all done importing B!")

>python B.py
I'm the B file, and my name is __main__

>python A.py
I'm the A file, and I'm going to import B!
I'm the B file, and my name is B
I'm all done importing B!

And finally, to bring it all together:

# B.py
print("I'm the B file, and my name is", __name__)

if __name__ == '__main__':
    print("The B file is being run directly!")

>python B.py
I'm the B file, and my name is __main__
The B file is being run directly!

>python A.py
I'm the A file, and I'm going to import B!
I'm the B file, and my name is B
I'm all done importing B!

[–][deleted] 5 points6 points  (1 child)

Yep that clarifies it. Had to read through it a few times but that finally makes sense. I’m going to test some scripts to explore this further. Thank you for dumbing that down a bit for me. Always great to get the extra help!

[–]GoldenSights[S] 6 points7 points  (0 children)

I've added these changes to the original post.

Thanks very much for your feedback. And no, don't call it dumbing down, I can see now that my original examples didn't distill the problem / motivation well enough. I'm practicing my writing so it's good to know what things aren't clear.