Domanda

Cosa fa se __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))
È stato utile?

Soluzione

Ogni volta che l'interprete Python legge un file sorgente, fa due cose:

  • imposta alcune variabili speciali come __name__ , e quindi

  • esegue tutto il codice trovato nel file.

Vediamo come funziona e come si collega alla tua domanda sui controlli __name__ che vediamo sempre negli script Python.

Esempio di codice

Usiamo un esempio di codice leggermente diverso per esplorare come funzionano le importazioni e gli script. Supponiamo che quanto segue sia in un file chiamato 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")

Variabili speciali

Quando l'interpeter Python legge un file sorgente, per prima cosa definisce alcune variabili speciali. In questo caso, ci preoccupiamo della variabile __name__ .

Quando il tuo modulo è il programma principale

Se stai eseguendo il tuo modulo (il file sorgente) come programma principale, ad esempio

python foo.py

l'interprete assegnerà la stringa codificata " __ main __ " alla variabile __name__ , ovvero

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

Quando il modulo è importato da un altro

D'altra parte, supponiamo che qualche altro modulo sia il programma principale e importa il tuo modulo. Questo significa che c'è una dichiarazione come questa nel programma principale, o in alcuni altri moduli il programma principale importa:

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

In questo caso, l'interprete esaminerà il nome del file del tuo modulo, foo.py , rimuoverà il .py e assegnerà quella stringa al < code> __ name__ , ovvero

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

Esecuzione del codice del modulo

Dopo aver impostato le variabili speciali, l'interprete esegue tutto il codice nel modulo, un'istruzione alla volta. Potresti voler aprire un'altra finestra sul lato con l'esempio di codice in modo da poter seguire questa spiegazione.

sempre

  1. Stampa la stringa " prima dell'importazione " (senza virgolette).

  2. Carica il modulo math e lo assegna a una variabile chiamata math . Ciò equivale a sostituire import math con il seguente (si noti che __import__ è una funzione di basso livello in Python che accetta una stringa e attiva l'importazione effettiva):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
  1. Stampa la stringa " prima della funzioneA " .

  2. Esegue il blocco def , creando un oggetto funzione, quindi assegnando quell'oggetto funzione a una variabile chiamata functionA.

  3. Stampa la stringa " prima della funzioneB " .

  4. Esegue il secondo blocco def , creando un altro oggetto funzione, quindi assegnandolo a una variabile chiamata functionB.

  5. Stampa la stringa " prima di __name__ guard " .

Solo quando il tuo modulo è il programma principale

  1. Se il tuo modulo è il programma principale, vedrà che __name__ era effettivamente impostato su " __ main __ " e chiama le due funzioni, stampando le stringhe < codice> " Funzione A " e " Funzione B 10.0 " .

Solo quando il tuo modulo è importato da un altro

  1. ( invece ) Se il tuo modulo non è il programma principale ma è stato importato da un altro, allora __name__ sarà " foo " , non " __ main __ " e salterà il corpo dell'istruzione if .

sempre

  1. Stampa la stringa " dopo __name__ guard " in entrambe le situazioni.

Sommario

In sintesi, ecco cosa sarebbe stampato nei due casi:

# 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

Perché funziona in questo modo?

Potresti naturalmente chiederti perché qualcuno vorrebbe questo. Bene, a volte vuoi scrivere un file .py che può essere sia usato da altri programmi e / o moduli come modulo, sia come programma principale stesso. Esempi:

  • Il tuo modulo è una libreria, ma vuoi avere una modalità script in cui esegue alcuni test unitari o una demo.

  • Il tuo modulo viene utilizzato solo come programma principale, ma ha alcuni test unitari e il framework di test funziona importando file .py come il tuo script ed eseguendo speciali funzioni di test. Non vuoi che provi a eseguire lo script solo perché sta importando il modulo.

  • Il tuo modulo viene utilizzato principalmente come programma principale, ma fornisce anche un'API intuitiva per i programmatori per utenti esperti.

Al di là di questi esempi, è elegante che eseguire uno script in Python stia semplicemente impostando alcune variabili magiche e importando lo script. & Quot; Corsa " lo script è un effetto collaterale dell'importazione del modulo dello script.

Food for Thought

  • Domanda: posso avere più blocchi __name__ ? Risposta: è strano farlo, ma la lingua non ti fermerà.

  • Supponiamo che quanto segue sia foo2.py . Cosa succede se dici python foo2.py sulla riga di comando? Perché?

# 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")
  • Ora, scopri cosa accadrà se rimuovi il __name__ in 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")
  • Cosa farà questo se usato come script? Se importato come modulo?
# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")

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

Altri suggerimenti

Quando lo script viene eseguito passandolo come comando all'interprete Python,

python myscript.py

viene eseguito tutto il codice che si trova al livello di rientro 0. Le funzioni e le classi definite sono ben definite, ma nessuno del loro codice viene eseguito. A differenza di altre lingue, non esiste alcuna funzione main () che viene eseguita automaticamente - la funzione main () è implicitamente tutto il codice al livello superiore.

In questo caso, il codice di livello superiore è un blocco if . __name__ è una variabile incorporata che valuta il nome del modulo corrente. Tuttavia, se un modulo viene eseguito direttamente (come in myscript.py sopra), allora __name__ viene invece impostato sulla stringa " __ main __ " . Pertanto, puoi verificare se il tuo script viene eseguito direttamente o importato da qualcos'altro testando

if __name__ == "__main__":
    ...

Se lo script viene importato in un altro modulo, verranno importate le sue varie definizioni di funzioni e classi e verrà eseguito il suo codice di livello superiore, ma il codice nel corpo di allora del if la clausola precedente non verrà eseguita poiché la condizione non è soddisfatta. Come esempio di base, considera i seguenti due script:

# 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")

Ora, se invochi l'interprete come

python one.py

L'output sarà

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

Se invece esegui two.py :

python two.py

Ottieni

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

Pertanto, quando viene caricato il modulo one , il suo __name__ è uguale a " one " anziché " __ main __ " .

La spiegazione più semplice per la variabile __name__ (imho) è la seguente:

Crea i seguenti file.

# a.py
import b

e

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

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

Eseguendoli otterrai questo output:

$ python a.py
Hello World from b!

Come puoi vedere, quando un modulo viene importato, Python imposta globals () ['__ name__'] in questo modulo sul nome del modulo. Inoltre, al momento dell'importazione viene eseguito tutto il codice nel modulo. Poiché l'istruzione if viene valutata in False questa parte non viene eseguita.

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

Come puoi vedere, quando viene eseguito un file, Python imposta globals () ['__ name__'] in questo file su " __ main __ " . Questa volta, l'istruzione if restituisce True ed è in esecuzione.

  

Cosa fa il se __name__ == " __ main __ " ;: ?

Per delineare le basi:

  • La variabile globale, __name__ , nel modulo che è il punto di accesso al programma, è '__main__' . Altrimenti, è il nome con cui importi il ??modulo.

  • Quindi, il codice nel blocco if verrà eseguito solo se il modulo è il punto di accesso al programma.

  • Consente al codice nel modulo di essere importabile da altri moduli, senza eseguire il blocco di codice sottostante durante l'importazione.


Perché ne abbiamo bisogno?

Sviluppo e test del codice

Supponi di scrivere uno script Python progettato per essere utilizzato come modulo:

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

potresti testare il modulo aggiungendo in fondo questa chiamata della funzione:

do_important()

ed eseguendolo (su un prompt dei comandi) con qualcosa del tipo:

~$ python important.py

Il problema

Tuttavia, se si desidera importare il modulo in un altro script:

import important

All'importazione, verrebbe chiamata la funzione do_important , quindi probabilmente commenterai la tua chiamata di funzione, do_important () , in fondo.

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

E poi dovrai ricordare se hai commentato o meno la tua chiamata alla funzione di test. E questa ulteriore complessità significherebbe che probabilmente dimenticherai, rendendo il tuo processo di sviluppo più problematico.

Un modo migliore

La variabile __name__ punta allo spazio dei nomi in qualsiasi momento si trovi l'interprete Python.

All'interno di un modulo importato, è il nome di quel modulo.

Ma all'interno del modulo primario (o una sessione interattiva di Python, ovvero Read, Eval, Print Loop o REPL dell'interprete) stai eseguendo qualsiasi cosa dal suo " __ main __ " .

Quindi, se controlli prima di eseguire:

if __name__ == "__main__":
    do_important()

Con quanto sopra, il tuo codice verrà eseguito solo quando lo esegui come modulo primario (o lo chiami intenzionalmente da un altro script).

Un modo ancora migliore

Tuttavia, esiste un modo Pythonic per migliorarlo.

Cosa succede se vogliamo eseguire questo processo aziendale dall'esterno del modulo?

Se inseriamo il codice che vogliamo esercitare mentre sviluppiamo e testiamo una funzione come questa e quindi controlliamo '__main__' immediatamente dopo:

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()

Ora abbiamo una funzione finale per la fine del nostro modulo che verrà eseguita se eseguiamo il modulo come modulo primario.

Consentirà al modulo e alle sue funzioni e classi di essere importati in altri script senza eseguire la funzione main e consentirà inoltre di chiamare il modulo (e le sue funzioni e classi) durante l'esecuzione da un altro modulo '__main__' , ovvero

import important
important.main()

Questo idioma può essere trovato anche nella documentazione di Python in una spiegazione del __main__ . Questo testo indica:

  

Questo modulo rappresenta l'ambito (altrimenti anonimo) in cui il   Il programma principale dell'interprete viene eseguito - i comandi vengono letti da   input standard, da un file di script o da un prompt interattivo. esso   è questo ambiente in cui la strana idiomatica "sceneggiatura condizionale"   causa l'esecuzione di uno script:

if __name__ == '__main__':
    main()

se __name__ == " __ main __ " è la parte che viene eseguita quando lo script viene eseguito da (diciamo) la riga di comando usando un comando come python myscript.py .

  

Cosa fa se __name__ == " __ main __ " ;: ?

__name__ è una variabile globale (in Python, globale significa in realtà a livello di modulo ) presente in tutti gli spazi dei nomi. In genere è il nome del modulo (come tipo str ).

Come unico caso speciale, tuttavia, in qualunque processo Python tu esegua, come in mycode.py:

python mycode.py

allo spazio dei nomi globale altrimenti anonimo viene assegnato il valore di '__main__' al suo __name__ .

Pertanto, tra cui le righe finali

if __name__ == '__main__':
    main()
  • alla fine dello script mycode.py,
  • quando è il principale modulo entry-point che viene eseguito da un processo Python,

farà funzionare la funzione main definita in modo univoco.

Un altro vantaggio dell'utilizzo di questo costrutto: puoi anche importare il tuo codice come modulo in un altro script e quindi eseguire la funzione principale se e quando il tuo programma decide:

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top