Python ako je __name__ == __poglavlje__ Objašnjeno primjerima koda

Kada tumač Python čita Python datoteku, prvo postavlja nekoliko posebnih varijabli. Zatim izvršava kod iz datoteke.

Jedna od tih varijabli se zove __name__.

Ako slijedite ovaj članak korak po korak i pročitate njegove isječke koda, naučit ćete kako ga koristiti if __name__ == "__main__"i zašto je toliko važan.

Objašnjeni Python moduli

Python datoteke nazivaju se modulima i prepoznaju se prema .pynastavku datoteke. Modul može definirati funkcije, klase i varijable.

Dakle, kada tumač pokrene modul, __name__varijabla će se postaviti kao   __main__da je modul koji se izvodi glavni program.

Ali ako kod uvozi modul iz drugog modula, tada će __name__  varijabla biti postavljena na ime tog modula.

Pogledajmo primjer. Stvorite Python modul s imenom file_one.pyi zalijepite ovaj kôd najviše razine unutra:

# Python file one module print("File one __name__ is set to: {}" .format(__name__))

Pokretanjem ove datoteke vidjet ćete točno o čemu smo razgovarali. Varijabla __name__za ovaj modul postavljena je na __main__:

File one __name__ is set to: __main__

Sada dodajte drugu datoteku s imenom file_two.pyi zalijepite ovaj kod unutra:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) 

Također, modificirajte kod file_one.pyovako, tako da uvozimo file_twomodul:

# Python module to execute import file_two print("File one __name__ is set to: {}" .format(__name__)) 

file_onePonovno pokretanje našeg koda pokazat će da se __name__varijabla u file_onenije promijenila i da je i dalje postavljena na __main__. Ali sada je varijabla __name__in file_twopostavljena kao ime modula, dakle file_two.

Rezultat bi trebao izgledati ovako:

File two __name__ is set to: file_two File one __name__ is set to: __main__ 

Ali pokrenite file_twoizravno i vidjet ćete da je njegovo ime postavljeno na __main__:

File two __name__ is set to: __main__ 

Varijabla __name__za datoteku / modul koja se izvodi uvijek će biti __main__. No, __name__varijabla za sve ostale module koji se uvozi bit će postavljena na ime njihovog modula.

Konvencije o imenovanju datoteka Python

Uobičajeni način korištenja __name__i __main__izgleda ovako:

if __name__ == "__main__": Do something here 

Pogledajmo kako ovo funkcionira u stvarnom životu i kako zapravo koristiti ove varijable.

Izmijenite file_onei file_twoizgledajte ovako:

file_one:

# Python module to execute import file_two print("File one __name__ is set to: {}" .format(__name__)) if __name__ == "__main__": print("File one executed when ran directly") else: print("File one executed when imported") 

file_two:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) if __name__ == "__main__": print("File two executed when ran directly") else: print("File two executed when imported") 

Opet, prilikom pokretanja file_onevidjet ćete da je program prepoznao koji je od ova dva modula __main__i izvršio kôd prema našim prvim if elseizjavama.

Rezultat bi trebao izgledati ovako:

File two __name__ is set to: file_two File two executed when imported File one __name__ is set to: __main__ File one executed when ran directly 

Sada pokrenite file_twoi vidjet ćete da je __name__varijabla postavljena na __main__:

File two __name__ is set to: __main__ File two executed when ran directly 

Kada se moduli poput ovog uvezu i pokrenu, uvest će se njihove funkcije i izvršiti kôd najviše razine.

Da biste vidjeli ovaj postupak na djelu, izmijenite datoteke tako da izgledaju ovako:

file_one:

# Python module to execute import file_two print("File one __name__ is set to: {}" .format(__name__)) def function_one(): print("Function one is executed") def function_two(): print("Function two is executed") if __name__ == "__main__": print("File one executed when ran directly") else: print("File one executed when imported") 

file_two:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) def function_three(): print("Function three is executed") if __name__ == "__main__": print("File two executed when ran directly") else: print("File two executed when imported") 

Sad su funkcije učitane, ali se ne pokreću.

Da biste pokrenuli jednu od ovih funkcija, izmijenite if __name__ == "__main__"dio tako file_oneda izgleda ovako:

if __name__ == "__main__": print("File one executed when ran directly") function_two() else: print("File one executed when imported") 

Prilikom pokretanja file_onetrebali biste vidjeti ovako:

File two __name__ is set to: file_two File two executed when imported File one __name__ is set to: __main__ File one executed when ran directly Function two is executed 

Također, možete pokretati funkcije iz uvezenih datoteka. Da biste to učinili, izmijenite if __name__ == “__main__”dio file_oneda izgleda ovako:

if __name__ == "__main__": print("File one executed when ran directly") function_two() file_two.function_three() else: print("File one executed when imported") 

I možete očekivati ​​ovakav rezultat:

File two __name__ is set to: file_two File two executed when imported File one __name__ is set to: __main__ File one executed when ran directly Function two is executed Function three is executed 

Sad recimo da je file_twomodul zaista velik s puno funkcija (dvije u našem slučaju) i ne želite uvesti sve. Izmijenite file_twoda izgleda ovako:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) def function_three(): print("Function three is executed") def function_four(): print("Function four is executed") if __name__ == "__main__": print("File two executed when ran directly") else: print("File two executed when imported") 

And to import the specific functions from the module, use the from import block in the file_one file:

# Python module to execute from file_two import function_three print("File one __name__ is set to: {}" .format(__name__)) def function_one(): print("Function one is executed") def function_two(): print("Function two is executed") if __name__ == "__main__": print("File one executed when ran directly") function_two() function_three() else: print("File one executed when imported")

Conclusion

There is a really nice use case for the __name__ variable, whether you want a file that can be run as the main program or imported by other modules. 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. Reading the file executes all top level code, but not functions and classes (since they will only get imported).

Bra gjort! (That means "Well done" in Swedish!)

Check out more articles like this on my freeCodeCamp profile, Medium profile, and other fun stuff I build on my GitHub page.