Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does it do this ? if - __name__ == '__main__' [duplicate]

Tags:

python

Duplicate of:
What does if __name__== "__main__" do?

Consider this code:

if __name__ == '__main__':
    import pdb
    pdb.run("interact()\n")

What does the following line mean?

if(__name__=='__main__')

I fainted.

like image 325
zjm1126 Avatar asked Dec 29 '09 07:12

zjm1126


People also ask

What does if __ name __ == Main do in Python?

We can use an if __name__ == "__main__" block to allow or prevent parts of code from being run when the modules are imported. When the Python interpreter reads a file, the __name__ variable is set as __main__ if the module being run, or as the module's name if it is imported.

What is the point of if name == Main?

if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.

Why do we use __ name __ in Python?

__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.

What is '__ main __'?

__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.


2 Answers

__name__ is a variable automatically set in an executing python program. If you import your module from another program, __name__ will be set to the name of the module. If you run your program directly, __name__ will be set to __main__.

Therefore, if you want some things to happen only if you're running your program from the command line and not when imported (eg. unit tests for a library), you can use the

if __name__ == "__main__":
  # will run only if module directly run
  print "I am being run directly"
else:
  # will run only if module imported
  print "I am being imported"

trick. It's a common Python idiom.

like image 126
Noufal Ibrahim Avatar answered Sep 29 '22 22:09

Noufal Ibrahim


This will be true if this module is being run as a standalone program. That way, something can act either as a module imported by another program, or a standalone program, but only execute the code in the if statement if executed as a program.

like image 31
Brian Campbell Avatar answered Sep 29 '22 23:09

Brian Campbell