0
#some.py

print(__name__)

On REPL, importing the above python code outputs filename.

>>> import some
some

While running the same script it outputs __main__,

 E:\> python some.py
__main__

Why isn't the results identical and what is the difference between two approaches?

Abhinav Kinagi
  • 3,653
  • 2
  • 27
  • 43

2 Answers2

0

That is the main intent behind __name__.

When you run the script with __name__ in it directly like python samp.py, the __name__ returns __main__.

When you import the script which has __name__, the __name__ would be the name of the script like some.

Underoos
  • 4,708
  • 8
  • 42
  • 85
0

__name__ is a built-in variable which evaluates to the name of the current module.

Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below.

when some.py is run directly, the interpreter sets the name variable as main and when it is run through some.py by importing, the name variable is set as the name of the python script.

I hope this helps.

Shishir Naresh
  • 743
  • 4
  • 10