Question

Que fait le si __name__ == " __ main __ ":: ?

# Threading example
import time, thread

def myfunction(string, sleeptime, lock, *args):
    while True:
        lock.acquire()
        time.sleep(sleeptime)
        lock.release()
        time.sleep(sleeptime)

if __name__ == "__main__":
    lock = thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
Était-ce utile?

La solution

Chaque fois que l'interprète Python lit un fichier source, il fait deux choses:

  • définit quelques variables spéciales telles que __ nom __ , puis

  • il exécute tout le code présent dans le fichier.

Voyons comment cela fonctionne et comment cela se rapporte à votre question sur les vérifications __ nom __ que nous voyons toujours dans les scripts Python.

Exemple de code

Utilisons un exemple de code légèrement différent pour explorer le fonctionnement des importations et des scripts. Supposons que ce qui suit se trouve dans un fichier nommé foo.py .

# Suppose this is foo.py.

print("before import")
import math

print("before functionA")
def functionA():
    print("Function A")

print("before functionB")
def functionB():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    functionA()
    functionB()
print("after __name__ guard")

Variables spéciales

Lorsque l’interpréteur Python lit un fichier source, il définit d’abord quelques variables spéciales. Dans ce cas, nous nous soucions de la variable __ name __ .

Lorsque votre module est le programme principal

Si vous exécutez votre module (le fichier source) en tant que programme principal, par exemple.

python foo.py

l'interprète assigne la chaîne codée en dur " __ main __ " à la variable __ nom __ , i.e.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 

Lorsque votre module est importé par un autre

D'autre part, supposons qu'un autre module soit le programme principal et qu'il importe votre module. Cela signifie qu'il existe une déclaration comme celle-ci dans le programme principal ou dans un autre module importé par le programme principal:

# Suppose this is in some other main program.
import foo

Dans ce cas, l'interpréteur examinera le nom du fichier de votre module, foo.py , supprimera le .py et affectera cette chaîne au < code> __ nom __ variable, c.-à-d.

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

Exécution du code du module

Une fois les variables spéciales définies, l'interpréteur exécute tout le code du module, une instruction à la fois. Vous voudrez peut-être ouvrir une autre fenêtre sur le côté avec l'exemple de code pour pouvoir suivre cette explication.

Toujours

  1. Il imprime la chaîne "avant l'importation" (sans les guillemets).

  2. Il charge le module math et l'assigne à une variable appelée math . Ceci équivaut à remplacer import math par ce qui suit (notez que __ import __ est une fonction de bas niveau en Python qui prend une chaîne et déclenche l'importation réelle):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
  1. Il imprime la chaîne "avant la fonction A" .

  2. Il exécute le bloc def en créant un objet fonction, puis en l'affectant à une variable appelée functionA .

  3. Il imprime la chaîne "avant la fonction B" .

  4. Il exécute le deuxième bloc def en créant un autre objet fonction, puis en l'affectant à une variable appelée functionB .

  5. Il imprime la chaîne " avant __name__ guard & .

Uniquement si votre module est le programme principal

  1. Si votre module est le programme principal, il verra que __ nom __ a bien été défini sur " __ main __ " et appelle les deux fonctions en imprimant les chaînes < code> "Fonction A" et "Fonction B 10.0" .

Seulement lorsque votre module est importé par un autre

  1. ( à la place ) Si votre module n'est pas le programme principal mais a été importé par un autre, __ nom __ sera " foo " , pas "__ main __" , et le contenu de l'instruction if sera ignoré.

Toujours

  1. Cela imprimera la chaîne " après __name__ guard & dans les deux situations.

Résumé

En résumé, voici ce qui serait imprimé dans les deux cas:

# What gets printed if foo is the main program
before import
before functionA
before functionB
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before functionA
before functionB
before __name__ guard
after __name__ guard

Pourquoi cela fonctionne-t-il de cette façon?

Vous pourriez naturellement vous demander pourquoi quelqu'un voudrait cela. Parfois, vous souhaitez écrire un fichier .py qui peut être utilisé par d’autres programmes et / ou modules en tant que module et peut également être exécuté en tant que programme principal. Exemples:

  • Votre module est une bibliothèque, mais vous souhaitez utiliser un mode script dans lequel il exécute des tests unitaires ou une démonstration.

  • Votre module est uniquement utilisé comme programme principal, mais il comporte des tests unitaires et le framework de test fonctionne en important des fichiers .py tels que votre script et en exécutant des fonctions de test spéciales. Vous ne voulez pas qu'il essaie d'exécuter le script simplement parce qu'il importe le module.

  • Votre module est principalement utilisé en tant que programme principal, mais il fournit également une API conviviale pour les programmeurs pour les utilisateurs avancés.

Au-delà de ces exemples, il est élégant que l’exécution d’un script en Python consiste simplement à configurer quelques variables magiques et à importer le script. " En cours " le script est un effet secondaire de l'importation du module du script.

Matière à réflexion

  • Question: Puis-je avoir plusieurs blocs de contrôle __ nom __ ? Réponse: c'est étrange de le faire, mais la langue ne vous arrêtera pas.

  • Supposons que ce qui suit se trouve dans foo2.py . Que se passe-t-il si vous dites python foo2.py sur la ligne de commande? Pourquoi?

# Suppose this is foo2.py.

def functionA():
    print("a1")
    from foo2 import functionB
    print("a2")
    functionB()
    print("a3")

def functionB():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    functionA()
    print("m2")
print("t2")
  • Maintenant, déterminez ce qui se passera si vous supprimez le __ nom __ dans foo3.py :
# Suppose this is foo3.py.

def functionA():
    print("a1")
    from foo3 import functionB
    print("a2")
    functionB()
    print("a3")

def functionB():
    print("b")

print("t1")
print("m1")
functionA()
print("m2")
print("t2")
  • Qu'est-ce que cela fera s'il est utilisé comme script? Lors de l'importation en tant que module?
# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")

print("before __name__ guard")
if __name__ == "__main__":
    bar()
print("after __name__ guard")

Autres conseils

Lorsque votre script est exécuté en le passant en tant que commande à l'interpréteur Python,

python myscript.py

tout le code au niveau d'indentation 0 est exécuté. Les fonctions et les classes qui sont définies sont bien définies, mais aucun de leur code n'est exécuté. Contrairement à d'autres langages, il n'y a pas de fonction main () qui s'exécute automatiquement - la fonction main () correspond implicitement à tout le code situé au niveau supérieur.

Dans ce cas, le code de niveau supérieur est un bloc si . __ name __ est une variable intégrée qui correspond au nom du module actuel. Toutefois, si un module est exécuté directement (comme dans myscript.py ci-dessus), __ name __ est alors défini sur la chaîne " __ main __ & <; code >. Ainsi, vous pouvez tester si votre script est exécuté directement ou importé par quelque chose d’autre en testant

if __name__ == "__main__":
    ...

Si votre script est importé dans un autre module, ses diverses définitions de fonctions et de classes seront importées et son code de niveau supérieur sera exécuté, mais le code situé dans le corps alors du si La clause ci-dessus ne sera pas exécutée car la condition n'est pas remplie. A titre d’exemple, considérons les deux scripts suivants:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")
# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

Maintenant, si vous appelez l'interprète en tant que

python one.py

Le résultat sera

top-level in one.py
one.py is being run directly

Si vous exécutez two.py à la place:

python two.py

vous obtenez

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Ainsi, lorsque le module one est chargé, son __ nom __ est égal à "un" au lieu de "__ main __" .

L'explication la plus simple de la variable __ name __ (imho) est la suivante:

Créez les fichiers suivants.

# a.py
import b

et

# b.py
print "Hello World from %s!" % __name__

if __name__ == '__main__':
    print "Hello World again from %s!" % __name__

Si vous les exécutez, vous obtiendrez cette sortie:

$ python a.py
Hello World from b!

Comme vous pouvez le constater, lorsqu'un module est importé, Python attribue à globals () ['__ name __'] de ce module le nom du module. En outre, lors de l'importation, tout le code du module est en cours d'exécution. Comme l'instruction if est évaluée à False , cette partie n'est pas exécutée.

$ python b.py
Hello World from __main__!
Hello World again from __main__!

Comme vous pouvez le constater, lorsqu'un fichier est exécuté, Python attribue à globals () ['__ name __'] de ce fichier la valeur " __ main __ " . Cette fois, l'instruction if est évaluée à True et est en cours d'exécution.

  

Que fait le si __name__ == "__ main __": ?

Pour décrire les bases:

  • La variable globale, __ nom __ , dans le module qui constitue le point d'entrée de votre programme, est '__ main __' . Sinon, c'est le nom par lequel vous importez le module.

  • Donc, codez sous le bloc si ne fonctionnera que si le module est le point d'entrée de votre programme.

  • Il permet au code du module d'être importé par d'autres modules, sans exécuter le bloc de code ci-dessous lors de l'importation.

Pourquoi avons-nous besoin de cela?

Développer et tester votre code

Dites que vous écrivez un script Python conçu pour être utilisé comme module:

def do_important():
    """This function does something very important"""

Vous pouvez tester le module en ajoutant cet appel de la fonction au bas de la page:

do_important()

et l'exécuter (à l'invite de commande) avec quelque chose comme:

~$ python important.py

Le problème

Toutefois, si vous souhaitez importer le module dans un autre script:

import important

Lors de l'importation, la fonction do_important serait appelée. Vous devriez donc probablement commenter votre appel de fonction, do_important () , en bas.

# do_important() # I must remember to uncomment to execute this!

Ensuite, vous devrez vous rappeler si vous avez commenté votre appel de fonction de test. Et cette complexité supplémentaire signifierait que vous oublierez probablement, rendant votre processus de développement plus gênant.

Une meilleure façon

La variable __ nom __ pointe vers l’espace de nommage où que l’interpréteur Python se trouve.

Dans un module importé, c'est le nom de ce module.

Mais à l'intérieur du module principal (ou d'une session Python interactive, c'est-à-dire les fonctions Read, Eval, Print Loop ou REPL de l'interpréteur), vous exécutez tout ce qui se trouve dans son "__ main __" .

Donc, si vous vérifiez avant d'exécuter:

if __name__ == "__main__":
    do_important()

Avec ce qui précède, votre code ne sera exécuté que lorsque vous l'exécutez en tant que module principal (ou l'appelle intentionnellement à partir d'un autre script).

Encore mieux

Cependant, il existe un moyen pythonique d’améliorer cette situation.

Que faire si nous voulons exécuter ce processus technique de l'extérieur du module?

Si nous mettons le code que nous voulons exercer lorsque nous développons et testons une fonction comme celle-ci, nous vérifions ensuite '__ main __' immédiatement après:

def main():
    """business logic for when running this module as the primary one!"""
    setup()
    foo = do_important()
    bar = do_even_more_important(foo)
    for baz in bar:
        do_super_important(baz)
    teardown()

# Here's our payoff idiom!
if __name__ == '__main__':
    main()

Nous avons maintenant une dernière fonction pour la fin de notre module qui sera exécutée si nous exécutons le module en tant que module principal.

Cela permettra au module, à ses fonctions et à ses classes d'être importés dans d'autres scripts sans exécuter la fonction main , et permettra également au module (ainsi qu'à ses fonctions et ses classes) d'être appelé lors de l'exécution. à partir d'un autre '__ main __' , c'est-à-dire

import important
important.main()

Cet idiome peut également être trouvé dans la documentation Python dans une explication du __main __ module. Ce texte indique:

  

Ce module représente la portée (sinon anonyme) dans laquelle le   programme principal de l’interprète s’exécute - les commandes lues soit   entrée standard, à partir d'un fichier de script ou d'une invite interactive. Il   est cet environnement dans lequel la strophe idiomatique de «script conditionnel»   provoque l'exécution d'un script:

if __name__ == '__main__':
    main()

if __name__ == " __ main __ " est la partie qui s'exécute lorsque le script est exécuté à partir de la ligne de commande à l'aide d'une commande du type python myscript.py . .

  

Que fait si __name__ == "__ main __": ?

__ nom __ est une variable globale (en Python, le terme global désigne en fait le niveau du module ) existant dans tous les espaces de noms. Il s’agit généralement du nom du module (sous la forme d'un type str ).

Cependant, comme seul cas particulier, quel que soit le processus Python que vous exécutez, comme dans mycode.py:

python mycode.py

la valeur '__ main __' est attribuée à l'espace de nom global autrement anonyme. Le __ nom __ lui est attribué.

Ainsi, en incluant les dernières lignes

if __name__ == '__main__':
    main()
  • à la fin de votre script mycode.py,
  • lorsqu'il s'agit du module principal d'entrée utilisé par un processus Python,

entraînera l'exécution de la fonction main définie par votre script.

Autre avantage de l’utilisation de cette construction: vous pouvez également importer votre code en tant que module dans un autre script, puis exécuter la fonction principale si et quand votre programme décide:

import mycode
# ... any amount of other code
mycode.main()

There are lots of different takes here on the mechanics of the code in question, the "How", but for me none of it made sense until I understood the "Why". This should be especially helpful for new programmers.

Take file "ab.py":

def a():
    print('A function in ab file');
a()

And a second file "xy.py":

import ab
def main():
    print('main function: this is where the action is')
def x():
    print ('peripheral task: might be useful in other projects')
x()
if __name__ == "__main__":
    main()

What is this code actually doing?

When you execute xy.py, you import ab. The import statement runs the module immediately on import, so ab's operations get executed before the remainder of xy's. Once finished with ab, it continues with xy.

The interpreter keeps track of which scripts are running with __name__. When you run a script - no matter what you've named it - the interpreter calls it "__main__", making it the master or 'home' script that gets returned to after running an external script.

Any other script that's called from this "__main__" script is assigned its filename as its __name__ (e.g., __name__ == "ab.py"). Hence, the line if __name__ == "__main__": is the interpreter's test to determine if it's interpreting/parsing the 'home' script that was initially executed, or if it's temporarily peeking into another (external) script. This gives the programmer flexibility to have the script behave differently if it's executed directly vs. called externally.

Let's step through the above code to understand what's happening, focusing first on the unindented lines and the order they appear in the scripts. Remember that function - or def - blocks don't do anything by themselves until they're called. What the interpreter might say if mumbled to itself:

  • Open xy.py as the 'home' file; call it "__main__" in the __name__ variable.
  • Import and open file with the __name__ == "ab.py".
  • Oh, a function. I'll remember that.
  • Ok, function a(); I just learned that. Printing 'A function in ab file'.
  • End of file; back to "__main__"!
  • Oh, a function. I'll remember that.
  • Another one.
  • Function x(); ok, printing 'peripheral task: might be useful in other projects'.
  • What's this? An if statement. Well, the condition has been met (the variable __name__ has been set to "__main__"), so I'll enter the main() function and print 'main function: this is where the action is'.

The bottom two lines mean: "If this is the "__main__" or 'home' script, execute the function called main()". That's why you'll see a def main(): block up top, which contains the main flow of the script's functionality.

Why implement this?

Remember what I said earlier about import statements? When you import a module it doesn't just 'recognize' it and wait for further instructions - it actually runs all the executable operations contained within the script. So, putting the meat of your script into the main() function effectively quarantines it, putting it in isolation so that it won't immediately run when imported by another script.

Again, there will be exceptions, but common practice is that main() doesn't usually get called externally. So you may be wondering one more thing: if we're not calling main(), why are we calling the script at all? It's because many people structure their scripts with standalone functions that are built to be run independent of the rest of the code in the file. They're then later called somewhere else in the body of the script. Which brings me to this:

But the code works without it

Yes, that's right. These separate functions can be called from an in-line script that's not contained inside a main() function. If you're accustomed (as I am, in my early learning stages of programming) to building in-line scripts that do exactly what you need, and you'll try to figure it out again if you ever need that operation again ... well, you're not used to this kind of internal structure to your code, because it's more complicated to build and it's not as intuitive to read.

But that's a script that probably can't have its functions called externally, because if it did it would immediately start calculating and assigning variables. And chances are if you're trying to re-use a function, your new script is related closely enough to the old one that there will be conflicting variables.

In splitting out independent functions, you gain the ability to re-use your previous work by calling them into another script. For example, "example.py" might import "xy.py" and call x(), making use of the 'x' function from "xy.py". (Maybe it's capitalizing the third word of a given text string; creating a NumPy array from a list of numbers and squaring them; or detrending a 3D surface. The possibilities are limitless.)

(As an aside, this question contains an answer by @kindall that finally helped me to understand - the why, not the how. Unfortunately it's been marked as a duplicate of this one, which I think is a mistake.)

When there are certain statements in our module (M.py) we want to be executed when it'll be running as main (not imported), we can place those statements (test-cases, print statements) under this if block.

As by default (when module running as main, not imported) the __name__ variable is set to "__main__", and when it'll be imported the __name__ variable will get a different value, most probably the name of the module ('M'). This is helpful in running different variants of a modules together, and separating their specific input & output statements and also if there are any test-cases.

In short, use this 'if __name__ == "main" ' block to prevent (certain) code from being run when the module is imported.

Let's look at the answer in a more abstract way:

Suppose we have this code in x.py:

...
<Block A>
if __name__ == '__main__':
    <Block B>
...

Blocks A and B are run when we are running "x.py".

But just block A (and not B) is run when we are running another module, "y.py" for example, in which x.y is imported and the code is run from there (like when a function in "x.py" is called from y.py).

Put simply, __name__ is a variable defined for each script that defines whether the script is being run as the main module or it is being run as an imported module.

So if we have two scripts;

#script1.py
print "Script 1's name: {}".format(__name__)

and

#script2.py
import script1
print "Script 2's name: {}".format(__name__)

The output from executing script1 is

Script 1's name: __main__

And the output from executing script2 is:

Script1's name is script1
Script 2's name: __main__

As you can see, __name__ tells us which code is the 'main' module. This is great, because you can just write code and not have to worry about structural issues like in C/C++, where, if a file does not implement a 'main' function then it cannot be compiled as an executable and if it does, it cannot then be used as a library.

Say you write a Python script that does something great and you implement a boatload of functions that are useful for other purposes. If I want to use them I can just import your script and use them without executing your program (given that your code only executes within the if __name__ == "__main__": context). Whereas in C/C++ you would have to portion out those pieces into a separate module that then includes the file. Picture the situation below;

Complicated importing in C

The arrows are import links. For three modules each trying to include the previous modules code there are six files (nine, counting the implementation files) and five links. This makes it difficult to include other code into a C project unless it is compiled specifically as a library. Now picture it for Python:

Elegant importing in Python

You write a module, and if someone wants to use your code they just import it and the __name__ variable can help to separate the executable portion of the program from the library part.

When you run Python interactively the local __name__ variable is assigned a value of __main__. Likewise, when you execute a Python module from the command line, rather than importing it into another module, its __name__ attribute is assigned a value of __main__, rather than the actual name of the module. In this way, modules can look at their own __name__ value to determine for themselves how they are being used, whether as support for another program or as the main application executed from the command line. Thus, the following idiom is quite common in Python modules:

if __name__ == '__main__':
    # Do something appropriate here, like calling a
    # main() function defined elsewhere in this module.
    main()
else:
    # Do nothing. This module has been imported by another
    # module that wants to make use of the functions,
    # classes and other useful bits it has defined.

Consider:

if __name__ == "__main__":
    main()

It checks if the __name__ attribute of the Python script is "__main__". In other words, if the program itself is executed, the attribute will be __main__, so the program will be executed (in this case the main() function).

However, if your Python script is used by a module, any code outside of the if statement will be executed, so if \__name__ == "\__main__" is used just to check if the program is used as a module or not, and therefore decides whether to run the code.

Before explaining anything about if __name__ == '__main__' it is important to understand what __name__ is and what it does.

What is __name__?

__name__ is a DunderAlias - can be thought of as a global variable (accessible from modules) and works in a similar way to global.

It is a string (global as mentioned above) as indicated by type(__name__) (yielding <class 'str'>), and is an inbuilt standard for both Python 3 and Python 2 versions.

Where:

It can not only be used in scripts but can also be found in both the interpreter and modules/packages.

Interpreter:

>>> print(__name__)
__main__
>>>

Script:

test_file.py:

print(__name__)

Resulting in __main__

Module or package:

somefile.py:

def somefunction():
    print(__name__)

test_file.py:

import somefile
somefile.somefunction()

Resulting in somefile

Notice that when used in a package or module, __name__ takes the name of the file. The path of the actual module or package path is not given, but has its own DunderAlias __file__, that allows for this.

You should see that, where __name__, where it is the main file (or program) will always return __main__, and if it is a module/package, or anything that is running off some other Python script, will return the name of the file where it has originated from.

Practice:

Being a variable means that it's value can be overwritten ("can" does not mean "should"), overwriting the value of __name__ will result in a lack of readability. So do not do it, for any reason. If you need a variable define a new variable.

It is always assumed that the value of __name__ to be __main__ or the name of the file. Once again changing this default value will cause more confusion that it will do good, causing problems further down the line.

example:

>>> __name__ = 'Horrify' # Change default from __main__
>>> if __name__ == 'Horrify': print(__name__)
...
>>> else: print('Not Horrify')
...
Horrify
>>>

It is considered good practice in general to include the if __name__ == '__main__' in scripts.

Now to answer if __name__ == '__main__':

Now we know the behaviour of __name__ things become clearer:

An if is a flow control statement that contains the block of code will execute if the value given is true. We have seen that __name__ can take either __main__ or the file name it has been imported from.

This means that if __name__ is equal to __main__ then the file must be the main file and must actually be running (or it is the interpreter), not a module or package imported into the script.

If indeed __name__ does take the value of __main__ then whatever is in that block of code will execute.

This tells us that if the file running is the main file (or you are running from the interpreter directly) then that condition must execute. If it is a package then it should not, and the value will not be __main__.

Modules:

__name__ can also be used in modules to define the name of a module

Variants:

It is also possible to do other, less common but useful things with __name__, some I will show here:

Executing only if the file is a module or package:

if __name__ != '__main__':
    # Do some useful things 

Running one condition if the file is the main one and another if it is not:

if __name__ == '__main__':
    # Execute something
else:
    # Do some useful things

You can also use it to provide runnable help functions/utilities on packages and modules without the elaborate use of libraries.

It also allows modules to be run from the command line as main scripts, which can be also very useful.

I think it's best to break the answer in depth and in simple words:

__name__: Every module in Python has a special attribute called __name__. It is a built-in variable that returns the name of the module.

__main__: Like other programming languages, Python too has an execution entry point, i.e., main. '__main__' is the name of the scope in which top-level code executes. Basically you have two ways of using a Python module: Run it directly as a script, or import it. When a module is run as a script, its __name__ is set to __main__.

Thus, the value of the __name__ attribute is set to __main__ when the module is run as the main program. Otherwise the value of __name__ is set to contain the name of the module.

It is a special for when a Python file is called from the command line. This is typically used to call a "main()" function or execute other appropriate startup code, like commandline arguments handling for instance.

It could be written in several ways. Another is:

def some_function_for_instance_main():
    dosomething()


__name__ == '__main__' and some_function_for_instance_main()

I am not saying you should use this in production code, but it serves to illustrate that there is nothing "magical" about if __name__ == '__main__'. It is a good convention for invoking a main function in Python files.

There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the __name__ variable/attribute:

When Python loads a source code file, it executes all of the code found in it. (Note that it doesn't call all of the methods and functions defined in the file, but it does define them.)

Before the interpreter executes the source code file though, it defines a few special variables for that file; __name__ is one of those special variables that Python automatically defines for each source code file.

If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special __name__ variable for this file to have a value "__main__".

If this is being imported from another module, __name__ will be set to that module's name.

So, in your example in part:

if __name__ == "__main__":
   lock = thread.allocate_lock()
   thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
   thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

means that the code block:

lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of __name__ will not equal to "main" in that particular instance.

Hope this helps out.

if __name__ == "__main__": is basically the top-level script environment, and it specifies the interpreter that ('I have the highest priority to be executed first').

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

if __name__ == "__main__":
    # Execute only if run as a script
    main()

The reason for

if __name__ == "__main__":
    main()

is primarily to avoid the import lock problems that would arise from having code directly imported. You want main() to run if your file was directly invoked (that's the __name__ == "__main__" case), but if your code was imported then the importer has to enter your code from the true main module to avoid import lock problems.

A side-effect is that you automatically sign on to a methodology that supports multiple entry points. You can run your program using main() as the entry point, but you don't have to. While setup.py expects main(), other tools use alternate entry points. For example, to run your file as a gunicorn process, you define an app() function instead of a main(). Just as with setup.py, gunicorn imports your code so you don't want it do do anything while it's being imported (because of the import lock issue).

I've been reading so much throughout the answers on this page. I would say, if you know the thing, for sure you will understand those answers, otherwise, you are still confused.

To be short, you need to know several points:

  1. import a action actually runs all that can be ran in "a"

  2. Because of point 1, you may not want everything to be run in "a" when importing it

  3. To solve the problem in point 2, python allows you to put a condition check

  4. __name__ is an implicit variable in all .py modules; when a.py is imported, the value of __name__ of a.py module is set to its file name "a"; when a.py is run directly using "python a.py", which means a.py is the entry point, then the value of __name__ of a.py module is set to a string __main__

  5. Based on the mechanism how python sets the variable __name__ for each module, do you know how to achieve point 3? The answer is fairly easy, right? Put a if condition: if __name__ == "__main__": ...; you can even put if __name__ == "a" depending on your functional need

The important thing that python is special at is point 4! The rest is just basic logic.

Consider:

print __name__

The output for the above is __main__.

if __name__ == "__main__":
  print "direct method"

The above statement is true and prints "direct method". Suppose if they imported this class in another class it doesn't print "direct method" because, while importing, it will set __name__ equal to "first model name".

You can make the file usable as a script as well as an importable module.

fibo.py (a module named fibo)

# Other modules can IMPORT this MODULE to use the function fib
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

# This allows the file to be used as a SCRIPT
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

Reference: https://docs.python.org/3.5/tutorial/modules.html

This answer is for Java programmers learning Python. Every Java file typically contains one public class. You can use that class in two ways:

  1. Call the class from other files. You just have to import it in the calling program.

  2. Run the class stand alone, for testing purposes.

For the latter case, the class should contain a public static void main() method. In Python this purpose is served by the globally defined label '__main__'.

If this .py file are imported by other .py files, the code under "the if statement" will not be executed.

If this .py are run by python this_py.py under shell, or double clicked in Windows. the code under "the if statement" will be executed.

It is usually written for testing.

Create a file, a.py:

print(__name__) # It will print out __main__

__name__ is always equal to __main__ whenever that file is run directly showing that this is the main file.

Create another file, b.py, in the same directory:

import a  # Prints a

Run it. It will print a, i.e., the name of the file which is imported.

So, to show two different behavior of the same file, this is a commonly used trick:

# Code to be run when imported into another python file

if __name__ == '__main__':
    # Code to be run only when run directly

if name == 'main':

We see if __name__ == '__main__': quite often.

It checks if a module is being imported or not.

In other words, the code within the if block will be executed only when the code runs directly. Here directly means not imported.

Let's see what it does using a simple code that prints the name of the module:

# test.py
def test():
   print('test module name=%s' %(__name__))

if __name__ == '__main__':
   print('call test()')
   test()

If we run the code directly via python test.py, the module name is __main__:

call test()
test module name=__main__

All the answers have pretty much explained the functionality. But I will provide one example of its usage which might help clearing out the concept further.

Assume that you have two Python files, a.py and b.py. Now, a.py imports b.py. We run the a.py file, where the "import b.py" code is executed first. Before the rest of the a.py code runs, the code in the file b.py must run completely.

In the b.py code there is some code that is exclusive to that file b.py and we don't want any other file (other than b.py file), that has imported the b.py file, to run it.

So that is what this line of code checks. If it is the main file (i.e., b.py) running the code, which in this case it is not (a.py is the main file running), then only the code gets executed.

Simply it is the entry point to run the file like the main function in the C programming language.

Every module in python has a attribute which is called as name . The value of name attribute is 'main' when module run directly. Otherwise the value of name is the name of the module.

Small example to explain in short.

#Script test.py

apple = 42

def hello_world():
    print("I am inside hello_world")

if __name__ == "__main__":
    print("Value of __name__ is: ", __name__)
    print("Going to call hello_world")
    hello_world()

We can execute this directly as

python test.py  

Output

Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world

Now suppose we call above script from other script

#script external_calling.py

import test
print(test.apple)
test.hello_world()

print(test.__name__)

When you execute this

python external_calling.py

Output

42
I am inside hello_world
test

So, above is self explanatory that when you call test from other script, if loop name in test.py will not execute.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top