What does if __name__ == "__main__": bash?

What does if __name__ ==

What does this bash, and wherefore ought to 1 see the if message?

if __name__ == "__main__": print("Hello, World!")

If you are attempting to adjacent a motion wherever person ought to beryllium utilizing this idiom and isn't, see closing arsenic a duplicate of Wherefore is Python moving my module once I import it, and however bash I halt it? alternatively. For questions wherever person merely hasn't referred to as immoderate capabilities, oregon incorrectly expects a relation named main to beryllium utilized arsenic an introduction component routinely, usage Wherefore doesn't the chief() relation tally once I commencement a Python book? Wherever does the book commencement moving?.


Abbreviated Reply

It's boilerplate codification that protects customers from unintentionally invoking the book once they didn't mean to. Present are any communal issues once the defender is omitted from a book:

  • If you import the guardless book successful different book (e.g. import my_script_without_a_name_eq_main_guard), past the second book volition set off the erstwhile to tally astatine import clip and utilizing the 2nd book's bid formation arguments. This is about ever a error.

  • If you person a customized people successful the guardless book and prevention it to a pickle record, past unpickling it successful different book volition set off an import of the guardless book, with the aforesaid issues outlined successful the former slug.

Agelong Reply

To amended realize wherefore and however this issues, we demand to return a measure backmost to realize however Python initializes scripts and however this interacts with its module import mechanics.

Every time the Python interpreter reads a origin record, it does 2 issues:

  • it units a fewer particular variables similar __name__, and past

  • it executes each of the codification recovered successful the record.

Fto's seat however this plant and however it relates to your motion astir the __name__ checks we ever seat successful Python scripts.

Codification Example

Fto's usage a somewhat antithetic codification example to research however imports and scripts activity. Say the pursuing is successful a record referred to as foo.py.

# Suppose this is foo.py.print("before import")import mathprint("before function_a")def function_a(): print("Function A")print("before function_b")def function_b(): print("Function B {}".format(math.sqrt(100)))print("before __name__ guard")if __name__ == '__main__': function_a() function_b()print("after __name__ guard")

Particular Variables

Once the Python interpreter reads a origin record, it archetypal defines a fewer particular variables. Successful this lawsuit, we attention astir the __name__ adaptable.

Once Your Module Is the Chief Programme

If you are moving your module (the origin record) arsenic the chief programme, e.g.

python foo.py

the interpreter volition delegate the difficult-coded drawstring "__main__" to the __name__ adaptable, i.e.

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

Once Your Module Is Imported By Different

Connected the another manus, say any another module is the chief programme and it imports your module. This means location's a message similar this successful the chief programme, oregon successful any another module the chief programme imports:

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

The interpreter volition hunt for your foo.py record (on with looking out for a fewer another variants), and anterior to executing that module, it volition delegate the sanction "foo" from the import message to the __name__ adaptable, i.e.

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

Executing the Module's Codification

Last the particular variables are fit ahead, the interpreter executes each the codification successful the module, 1 message astatine a clip. You whitethorn privation to unfastened different framework connected the broadside with the codification example truthful you tin travel on with this mentation.

Ever

  1. It prints the drawstring "before import" (with out quotes).

  2. It hundreds the math module and assigns it to a adaptable referred to as math. This is equal to changing import math with the pursuing (line that __import__ is a debased-flat relation successful Python that takes a drawstring and triggers the existent import):

# Find and load a module given its string name, "math",# then assign it to a local variable called math.math = __import__("math")
  1. It prints the drawstring "before function_a".

  2. It executes the def artifact, creating a relation entity, past assigning that relation entity to a adaptable referred to as function_a.

  3. It prints the drawstring "before function_b".

  4. It executes the 2nd def artifact, creating different relation entity, past assigning it to a adaptable referred to as function_b.

  5. It prints the drawstring "before __name__ guard".

Lone Once Your Module Is the Chief Programme

  1. If your module is the chief programme, past it volition seat that __name__ was so fit to "__main__" and it calls the 2 capabilities, printing the strings "Function A" and "Function B 10.0".

Lone Once Your Module Is Imported by Different

  1. (alternatively) If your module is not the chief programme however was imported by different 1, past __name__ volition beryllium "foo", not "__main__", and it'll skip the assemblage of the if message.

Ever

  1. It volition mark the drawstring "after __name__ guard" successful some conditions.

Abstract

Successful abstract, present's what'd beryllium printed successful the 2 instances:

# What gets printed if foo is the main programbefore importbefore function_abefore function_bbefore __name__ guardFunction AFunction B 10.0after __name__ guard
# What gets printed if foo is imported as a regular modulebefore importbefore function_abefore function_bbefore __name__ guardafter __name__ guard

Wherefore Does It Activity This Manner?

You mightiness course wonderment wherefore anyone would privation this. Fine, generally you privation to compose a .py record that tin beryllium some utilized by another applications and/oregon modules arsenic a module, and tin besides beryllium tally arsenic the chief programme itself. Examples:

  • Your module is a room, however you privation to person a book manner wherever it runs any part exams oregon a demo.

  • Your module is lone utilized arsenic a chief programme, however it has any part exams, and the investigating model plant by importing .py records-data similar your book and moving particular trial capabilities. You don't privation it to attempt moving the book conscionable due to the fact that it's importing the module.

  • Your module is largely utilized arsenic a chief programme, however it besides supplies a programmer-affable API for precocious customers.

Past these examples, it's elegant that moving a book successful Python is conscionable mounting ahead a fewer magic variables and importing the book. "Moving" the book is a broadside consequence of importing the book's module.

Nutrient for Idea

  • Motion: Tin I person aggregate __name__ checking blocks? Reply: it's unusual to bash truthful, however the communication received't halt you.

  • Say the pursuing is successful foo2.py. What occurs if you opportunity python foo2.py connected the bid-formation? Wherefore?

# Suppose this is foo2.py.import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpretersdef function_a(): print("a1") from foo2 import function_b print("a2") function_b() print("a3")def function_b(): print("b")print("t1")if __name__ == "__main__": print("m1") function_a() print("m2")print("t2") 
  • Present, fig retired what volition hap successful foo3.py (having eliminated the __name__ cheque):
# Suppose this is foo3.py.import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpretersdef function_a(): print("a1") from foo3 import function_b print("a2") function_b() print("a3")def function_b(): print("b")print("t1")print("m1")function_a()print("m2")print("t2")
  • What volition this bash once utilized arsenic a book? Once imported arsenic a 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")

Once your book is tally by passing it arsenic a bid to the Python interpreter,

python myscript.py

each of the codification that is astatine indentation flat Zero will get executed. Capabilities and courses that are outlined are, fine, outlined, however no of their codification will get tally. Dissimilar another languages, location's nary main() relation that will get tally mechanically - the main() relation is implicitly each the codification astatine the apical flat.

Successful this lawsuit, the apical-flat codification is an if artifact. __name__ is a constructed-successful adaptable which evaluates to the sanction of the actual module. Nevertheless, if a module is being tally straight (arsenic successful myscript.py supra), past __name__ alternatively is fit to the drawstring "__main__". Frankincense, you tin trial whether or not your book is being tally straight oregon being imported by thing other by investigating

if __name__ == "__main__": ...

If your book is being imported into different module, its assorted relation and people definitions volition beryllium imported and its apical-flat codification volition beryllium executed, however the codification successful the past-assemblage of the if clause supra received't acquire tally arsenic the information is not met. Arsenic a basal illustration, see the pursuing 2 scripts:

# file one.pydef 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.pyimport oneprint("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")

Present, if you invoke the interpreter arsenic

python one.py

The output volition beryllium

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

If you tally two.py alternatively:

python two.py

You acquire

top-level in one.pyone.py is being imported into another moduletop-level in two.pyfunc() in one.pytwo.py is being run directly

Frankincense, once module one will get loaded, its __name__ equals "one" alternatively of "__main__".


Successful the planet of Python programming, the formation if __name__ == "__main__": is a cornerstone for creating modular and reusable codification. It mightiness look similar a cryptic incantation astatine archetypal glimpse, however knowing its intent unlocks a deeper appreciation for however Python scripts are executed and organized. This concept is critical for distinguishing betwixt codification that ought to beryllium tally once a book is executed straight and codification that ought to beryllium tally once a book is imported arsenic a module into different book. Mastering this conception permits you to compose much organized, testable, and maintainable Python codification. This article volition demystify if __name__ == "__main__":, offering a broad mentation of its performance and applicable functions.

Knowing the Intent of if __name__ == "__main__":

The if __name__ == "__main__": message successful Python serves arsenic a conditional gatekeeper, figuring out whether or not a book is being tally arsenic the chief programme oregon being imported arsenic a module. Once a Python record is executed straight, Python assigns the drawstring "__main__" to the constructed-successful __name__ adaptable. If the book is imported into different book, the __name__ adaptable is assigned the sanction of the module. Frankincense, this conditional message permits you to specify which components of your codification ought to lone execute once the book is tally straight, and which components ought to beryllium disposable for usage once the book is imported arsenic a module. This discrimination is important for creating reusable codification that tin besides relation arsenic a standalone programme.

However Python Differentiates Betwixt Chief Applications and Modules

Python employs the __name__ adaptable to differentiate betwixt a book being executed straight and 1 being imported arsenic a module. Once you tally a Python record straight (e.g., python my_script.py), Python units the __name__ adaptable to "__main__". Nevertheless, once you import that aforesaid record into different book (e.g., import my_script), the __name__ adaptable inside my_script.py is fit to "my_script" (the module's sanction). This quality permits Python to execute definite codification blocks lone once the book is tally arsenic the chief programme, offering a mechanics to abstracted reusable module codification from execution-circumstantial codification. This is a cardinal facet of Python's modularity and codification formation.

  my_script.py def my_function(): print("This is my function.") if __name__ == "__main__": print("This script is being run directly.") my_function() else: print("This script is being imported as a module.")  

Applicable Functions and Advantages

The if __name__ == "__main__": concept provides many applicable advantages successful Python improvement. It permits you to make reusable modules that tin besides beryllium tally arsenic standalone applications, permitting for flexibility successful however your codification is utilized. This is peculiarly utile for investigating functions, wherever you tin see trial codification inside the module that lone runs once the module is executed straight. Moreover, it enhances codification formation by intelligibly separating the module's center performance from the book's circumstantial execution logic. By utilizing this conditional message, you tin make much maintainable, testable, and versatile Python codification. What does "utilization strict" bash palmy JavaScript, and what is the reasoning behind it? This separation of considerations is important for bigger initiatives and collaborative improvement environments.

See the pursuing illustration demonstrating the usage of if __name__ == "__main__"::

  my_module.py def calculate_area(length, width): """Calculates the area of a rectangle.""" return length  width def main(): length = 5 width = 10 area = calculate_area(length, width) print(f"The area of the rectangle is: {area}") if __name__ == "__main__": main()  

Successful this lawsuit, the calculate_area relation tin beryllium imported and utilized successful another scripts. The chief relation, which supplies circumstantial execution logic, lone runs once my_module.py is executed straight.

Characteristic Once Book is Tally Straight Once Book is Imported
__name__ Worth "__main__" Module Sanction (e.g., "my_module")
Codification Execution successful if __name__ == "__main__": Artifact Executes Does Not Execute
Intent Standalone Programme Execution Module for Reusable Codification

Present’s a database of cardinal advantages:

  • Modularity: Encourages modular plan by separating reusable codification from execution-circumstantial logic.
  • Testability: Permits you to see trial codification inside modules that lone runs once the module is executed straight.
  • Reusability: Makes it casual to import and usage features and courses outlined successful the module successful another scripts.
  • Formation: Enhances codification formation and maintainability.
"The if __name__ == "__main__": concept is a almighty implement for creating fine-structured and reusable Python codification."

By knowing and efficaciously using if __name__ == "__main__":, builders tin make much strong and maintainable Python functions. It's a cardinal conception that all Python programmer ought to maestro to compose cleanable and organized codification. See exploring additional assets connected Python modules and namespaces to deepen your knowing.

Successful abstract, the if __name__ == "__main__": message is an indispensable portion of penning modular and reusable Python codification. It permits you to abstracted the codification that ought to beryllium executed once a book is tally straight from the codification that ought to beryllium utilized once the book is imported arsenic a module. Knowing its relation and exertion is important for immoderate Python developer aiming to compose cleanable, organized, and businesslike codification. By utilizing this concept efficaciously, you tin heighten the testability, maintainability, and general choice of your Python initiatives. Larn much astir Python codification kind and Python modules for champion practices.


Why You Shouldn't Peel Your Hangnails 😖

Why You Shouldn't Peel Your Hangnails 😖 from Youtube.com

Previous Post Next Post

Formulario de contacto