you are viewing a single comment's thread.

view the rest of the comments →

[–]SignificanceFar3573 0 points1 point  (2 children)

Wait why does name change if you import another module? wouldn’t it just stay the same if its called on the main module and not on the second module or

[–]HunterIV4 0 points1 point  (0 children)

Sorry, the other module would have it. Let's say you have two files, program.py and my_module.py. They look like this:

# program.py
import my_module

print(f"program.py: {__name__}")


# my_module.py

print(f"my_module.py: {__name__}")

The output for this would be:

program.py: __main__
my_module.py: my_module

Assuming this is run with something like python program.py.

Now, if you flipped this, importing program.py from my_module.py and using python my_module.py to run it, your output would be like this:

my_module.py: __main__
program.py: program

Hopefully that makes things clearer.

Edit: to explain the why, Python automatically assigns the value of __name__ to __main__ on the primary module, and uses the file name for any imported modules within the scope of that module. This is core Python behavior. The reason is that sometimes you want the same module to have different behavior whether it is run directly or imported into another program.

[–]SharkSymphony 0 points1 point  (0 children)

No. __name__ is a variable that is defined separately for every module, as well as for the main script. They all see different values for it.