Is a block of code which only runs when it is called and they are also known as functions?
Short AnswerIt's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script: Show
Long AnswerTo better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism. Whenever the Python interpreter reads a source file, it does two things:
Let's see how this works and how it relates to your
question about the Code SampleLet's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called
Special VariablesWhen the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the When Your Module Is the Main Program If you are running your module (the source file) as the main program, e.g.
the interpreter will assign the hard-coded string
When Your Module Is Imported By Another On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:
The interpreter will search for your
Executing the Module's CodeAfter the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation. Always
Only When Your Module Is the Main Program
Only When Your Module Is Imported by Another
Always
Summary In summary, here's what'd be printed in the two cases:
Why Does It Work This Way?You might naturally wonder why anybody would want this. Well, sometimes you want to write a
Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module. Food for Thought
Neuron 4,6524 gold badges33 silver badges54 bronze badges answered Jan 7, 2009 at 4:26
Mr FoozMr Fooz 106k5 gold badges69 silver badges100 bronze badges 22 When your script is run by passing it as a command to the Python interpreter,
all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no In this case, the top-level code is an
If your
script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the
Now, if you invoke the interpreter as
The output will be
If you run
You get
Thus, when module
Tonechas 13k15 gold badges42 silver badges76 bronze badges answered Jan 7, 2009 at 4:28
Adam RosenfieldAdam Rosenfield 380k96 gold badges508 silver badges584 bronze badges 2 Create the following two files:
Now run each file individually. Running
When Running
When only the file
Mateen Ulhaq 22.3k16 gold badges86 silver badges127 bronze badges answered Jan 7, 2009 at 11:35
pi.pi. 20.5k7 gold badges38 silver badges59 bronze badges 0
To outline the basics:
Why do we need this? Developing and Testing Your CodeSay you're writing a Python script designed to be used as a module:
You could test the module by adding this call of the function to the bottom:
and running it (on a command prompt) with something like:
The ProblemHowever, if you want to import the module to another script:
On import, the
And then you'll have to remember whether or not you've commented out your test function call. And this extra complexity would mean you're likely to forget, making your development process more troublesome. A Better WayThe Inside an imported module, it's the name of that module. But inside the primary module (or an interactive Python session, i.e. the interpreter's Read, Eval, Print Loop, or REPL) you are running everything from its
So if you check before executing:
With the above, your code will only execute when you're running it as the primary module (or intentionally call it from another script). An Even Better WayThere's a Pythonic way to improve on this, though. What if we want to run this business process from outside the module? If we put the code we want to exercise as we develop and test in a function like this and then do our check for
We now have a final function for the end of our module that will run if we run the module as the primary module. It will allow the module and its functions and classes to be imported into other scripts without running the
This idiom can also be found in the Python documentation in an explanation of the
answered Nov 23, 2013 at 4:38
2
Mark Amery 133k78 gold badges395 silver badges443 bronze badges answered Jan 7, 2009 at 4:14
Harley HolcombeHarley Holcombe 170k15 gold badges69 silver badges63 bronze badges 2
As the only special case, however, in whatever Python process you run, as in mycode.py:
the otherwise anonymous global namespace is
assigned the value of Thus, including the final lines
will cause your script's uniquely defined Another benefit of using this construct: you can also import your code as a module in another script and then run the main function if and when your program decides:
Mateen Ulhaq 22.3k16 gold badges86 silver badges127 bronze badges answered Oct 14, 2014 at 20:22
0 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":
And a second file "xy.py":
When you execute The interpreter keeps track of which scripts are running with Any other script that's called from this 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
The bottom two lines mean: "If this is the
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 Again, there will be exceptions, but common practice is that
Yes, that's right. These separate functions can be called from an in-line script that's not contained inside a 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 (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.) answered Sep 29, 2016 at 4:33
joechojjoechoj 1,2899 silver badges12 bronze badges 0 The code under As an example, consider the following module
First possibility: Import
Now if you invoke
Note that only the top-level Second
possibility: Invoke Now if you run
For a more comprehensive explanation, you can read What does
answered Feb 1, 2020 at 13:26
1 When there are certain statements in our module ( As by default (when module running as main, not imported) the In short, use this '
answered Apr 3, 2013 at 14:09
Nabeel AhmedNabeel Ahmed 17.5k4 gold badges55 silver badges59 bronze badges 1 Put simply, So if we have two scripts;
and
The output from executing script1 is
And the output from executing script2 is:
As you can see, 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 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: You write a module, and if someone wants to use your code they just import it and the
answered Oct 15, 2016 at 9:07
redbanditredbandit 2,06215 silver badges11 bronze badges 1 Let's look at the answer in a more abstract way: Suppose we have this code in
Blocks A and B are run when we are running But just block A (and not B) is run when we are running another module,
kubuntu 2,5251 gold badge21 silver badges24 bronze badges answered Jan 20, 2015 at 17:48
AlisaAlisa 2,7623 gold badges30 silver badges44 bronze badges 0 To be short, you need to know several points:
The important thing that Python is special at is point 4! The rest is just basic logic. 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.
answered Jun 24, 2018 at 15:48
jackjack 1,58710 silver badges25 bronze badges 1 When you run Python interactively the local
answered Dec 11, 2013 at 11:23
ZainZain 1,1961 gold badge15 silver badges26 bronze badges Consider:
It checks if the However, if your Python script is used by a module, any code outside of the
tripleee 165k27 gold badges249 silver badges297 bronze badges answered Aug 22, 2017 at 18:53
LarryLarry 1,2522 gold badges14 silver badges20 bronze badges 0 Before explaining anything about What is __name__?
It is a string (global as mentioned above) as indicated by WhereIt can not only be used in scripts but can also be found in both the interpreter and modules/packages. Interpreter:
Script:test_file.py:
Resulting in Module or package:somefile.py:
test_file.py:
Resulting in Notice that when used in a package or module, You should see that, where PracticeBeing a variable means that it's value can be overwritten ("can" does not mean "should"), overwriting the value of It is always assumed that the value of Example:
It is considered good practice in general to include the Now to answer if __name__ == '__main__':Now we know the behaviour of An This means that if If indeed 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 Modules
VariantsIt is also possible to do other, less common but useful things with Executing only if the file is a module or package
Running one condition if the file is the main one and another if it is not
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.
tripleee 165k27 gold badges249 silver badges297 bronze badges answered Apr 3, 2018 at 19:32
XantiumXantium 10.6k10 gold badges58 silver badges87 bronze badges 0 I think it's best to break the answer in depth and in simple words:
Thus, the value of the
answered Nov 30, 2016 at 6:47
Taufiq RahmanTaufiq Rahman 5,4552 gold badges36 silver badges43 bronze badges 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:
I am not saying you should use this in production code, but it serves to illustrate that there is nothing "magical" about It just a convention for invoking a main function in Python files. answered Jan 24, 2013 at 13:48
Prof. FalkenProf. Falken 23.6k18 gold badges100 silver badges168 bronze badges 6 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:
means that the code block:
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. answered Nov 25, 2015 at 12:26
codewizardcodewizard 3763 silver badges8 bronze badges 1
answered Apr 24, 2016 at 8:23
The Gr8 AdakronThe Gr8 Adakron 1,1721 gold badge12 silver badges14 bronze badges Consider:
The output for the above is
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
simhumileco 28.7k16 gold badges126 silver badges106 bronze badges answered Jun 22, 2016 at 10:47
In simple words: The code you see under However, if you wish to import your Python file
tripleee 165k27 gold badges249 silver badges297 bronze badges answered Oct 22, 2020 at 18:01
fibo.py (a module named
Reference: https://docs.python.org/3.5/tutorial/modules.html answered Mar 13, 2017 at 21:44
kgf3JfUtWkgf3JfUtW 12.4k8 gold badges50 silver badges74 bronze badges The reason for
is primarily to avoid
the import lock problems that would arise from having code directly imported. You want A
side-effect is that you automatically sign on to a methodology that supports multiple entry points. You can run your program using answered Sep 22, 2017 at 18:32
personal_cloudpersonal_cloud 3,6502 gold badges25 silver badges32 bronze badges 0 If you are a beginner, probably the only answer you need right now is that this code is unnecessary for a simple script. It is only useful if you want to be able to In slightly different words, the In slightly more detail, let's say you have a simple script
Now, if you simply run
Now, you can't If you do want to be able to
Now, if you Actually, a better design still would be to isolate the reusable part (the actual calculation) from the user-visible input/output:
Now, you can (I called the function Similarly, you could Returning to the code in the question, I would similarly move the code from the
This changes the scope of the
(Unlike in languages like C, the name answered Oct 30, 2021 at 9:46
tripleeetripleee 165k27 gold badges249 silver badges297 bronze badges 3 Every
module in Python has an attribute called Small example to explain in short. Script test.py
We can execute this directly as
Output
Now suppose we call the above script from another script: Script external_calling.py
When you execute this,
Output
So, the above is self-explanatory that when you call test from another script, if loop
answered Jun 12, 2019 at 9:28
Rishi BansalRishi Bansal 3,4772 gold badges24 silver badges44 bronze badges This answer is for Java programmers learning Python. Every Java file typically contains one public class. You can use that class in two ways:
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
eyllanesc 226k18 gold badges135 silver badges203 bronze badges answered Oct 7, 2018 at 4:52
RajaRaja 96611 silver badges13 bronze badges 0 If this .py file are imported by
other .py files, the code under the If this .py are run by It is usually written for testing.
tripleee 165k27 gold badges249 silver badges297 bronze badges answered Jun 19, 2018 at 11:44
pah8Jpah8J 7777 silver badges15 bronze badges If the Python interpreter is running a particular module then the
When you run this script, it prints you can see me. a If you import this file, say A to file B, and execute the file B then b
answered Jul 30, 2019 at 16:22
We see if It checks if a module is being imported or not. In other words, the code within the Let's see what it does using a simple code that prints the name of the module:
If we run the code directly via
tripleee 165k27 gold badges249 silver badges297 bronze badges answered Apr 4, 2018 at 14:32
Ali HallajiAli Hallaji 2,9042 gold badges25 silver badges35 bronze badges 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.
answered May 4, 2018 at 8:25
What are functions in code?A function is simply a “chunk” of code that you can use over and over again, rather than writing it out multiple times. Functions enable programmers to break down or decompose a problem into smaller chunks, each of which performs a particular task.
What is a function call?A function call is an expression that passes control and arguments (if any) to a function and has the form: expression (expression-listopt) where expression is a function name or evaluates to a function address and expression-list is a list of expressions (separated by commas).
What are the types of functions in programming?There are 4 types of functions:. Functions with arguments and return values. This function has arguments and returns a value: ... . Functions with arguments and without return values. ... . Functions without arguments and with return values. ... . Functions without arguments and without return values.. What is called when a function is defined inside a class?In C++, a function contained within a class is called a Member function. Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier.
|