• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh

Should flow of this code involving main method not start from main method?

 
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have written the below python code:



When I run it, I was expecting it to start from main method and print 'hello from main' but it prints 'hello from beginning of script' and then 'hello from main'

Should this not begin execution from main method and print 'hello from main' and then the other one ?

thanks
 
Saloon Keeper
Posts: 12992
281
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why do you expect it to start running from main()?
 
Greenhorn
Posts: 1
Python Firefox Browser Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello from Japan!
Please forgive my English skills...
Usually, programs follows the rule of "First Comes, First Serves".
You have told the program to print "hello from beginning of the script" first,
and then to execute if statement.
I understand if you felt like main should be executed first because it is named "main", but
that is not the case.
Hope this helps!
 
Sheriff
Posts: 16205
270
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See what happens when you delete lines 4 and 5. That's how Python works.
 
Saloon Keeper
Posts: 23692
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Python is a linear language first, a procedural language second, and an object-oriented language third.

When a Python file is executed, stand-alone statements are executed in order from the top of the file and proceeding downwards. Any procedure and/or class definitions ("def" elements) are skipped over.

Python does not inherently understand "main". It's a convention, so if you remove the statement that calls main() - which, please note, is a stand-alone "if" statement, then main() will never execute.
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:See what happens when you delete lines 4 and 5. That's how Python works.



Then as expected the main method will not get called and it will not print 'hello from main'
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If means although Python has main method, it is not the entry point.
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hunter Gaio wrote:
I understand if you felt like main should be executed first because it is named "main", but
that is not the case.


I am trying to understand its significance, given that it is not the entry point.
 
Ranch Foreman
Posts: 415
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:I have written the below python code:



When I run it, I was expecting it to start from main method and print 'hello from main' but it prints 'hello from beginning of script' and then 'hello from main'

Should this not begin execution from main method and print 'hello from main' and then the other one ?

thanks



Hi Monica:

Your original code shown accidentally uses the assignment operator =, rather than the test for equivalence, ==
Python 3.9 screamed at me when I actually tried to execute that, so I am guessing that  typo wasn't in your original?
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry for the typo.Corrected it now.
 
Master Rancher
Posts: 3889
50
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:I am trying to understand its significance, given that it is not the entry point.


It has no particular significance.  People often write their code so that there is a method named main that is executed first, or at least early on.  But that is just a common practice -  the python interpreter does not require this, or care whether you have a method named main.  It cares what you actually tell it to do; it doesn't call main automatically.  In comparison, in Java the main method is called first, because Java has been set up that way, and the JVM expects to find a main() method to run when it starts up.  That's how Java was designed.  But, it's not how Python was designed.
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote:People often write their code so that there is a method named main that is executed first, or at least early on.  



By making sure that it is at the top most in the code ? (Since python executes top to bottom)
 
Mike Simmons
Master Rancher
Posts: 3889
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:

Mike Simmons wrote:People often write their code so that there is a method named main that is executed first, or at least early on.  



By making sure that it is at the top most in the code ? (Since python executes top to bottom)



Well, if you've got everything in one file, you would need to define main first, then invoke it.  Or you could put main in another file, and import the file, then invoke main().  There are various ways to put it together.  Here's an article describing common python best practices for main().
 
Jesse Silverman
Ranch Foreman
Posts: 415
10
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:

Mike Simmons wrote:People often write their code so that there is a method named main that is executed first, or at least early on.  



By making sure that it is at the top most in the code ? (Since python executes top to bottom)



No.  In Java having a one-file thing that we just quickly write and execute is quite new.  Most real programs have dozens or hundreds of classes in so many different files...

In Python, it was extremely common and is still usual even today to write some quick stuff that fits in one script:
monica_script.py

and just run it.

But a single script can also be considered as a module to be imported

import monica_module as mm

mm.do_stuff()

if you don't use the
if __name__ == '__main__':

protection around any bare code you have there, besides the definitions, then every single script that imports yours is going to see the things running, which is usually NOT what you want.

They are never going to change this behavior because they want it to be friendly for scripters who are just writing one-file solutions.

Additionally, except for __name__ changing and a few other things, I don't think Python is really thinking about whether a script is being run directly or just processed as an import

top to bottom is still important tho, unlike most languages invented since 1970, you can't call a function from a line higher up than where you defined it!

 
Jesse Silverman
Ranch Foreman
Posts: 415
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

Monica Shiralkar wrote:Sorry for the typo.Corrected it now.

Please don't. That makes JS' answer difficult to understand. Please post the new code; I have refused your edit.



That nobody noticed it justifies (at least partially) the ultra-paranoid practices of my co-workers (workplace standard in C/C++) where only

"value" == variable
would be allowed, and
variable == value

got rejected on code review.

Of course for consistency, they also did
NULL != ptr
too....

When I keep jumping back and forth between languages all day I forget some things, but that made me even more careful to spot the SQL-style = for == here.
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I did some changes in the script and have question based on that:

Test.py



Test1.py


On running Test1, it prints 'hello from test1' and 'hello from beginning of script'.


So code in main function is gaurded but so is the code inside my_function function. So how is main function different from my_function?

 
Marshal
Posts: 72926
330
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:. . . they also did
NULL != ptr
too....
. . .

It's not just consistency. That sort of thing might be useful in C/C++ but Java® code will fail to compile if you write if (xyz = null) ... I think that that errors are much likelier with something == somethingElse than with !=.
 
Jesse Silverman
Ranch Foreman
Posts: 415
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:I did some changes in the script and have question based on that:
...

So code in main function is gaurded but so is the code inside my_function function. So how is main function different from my_function?



I believe it is not any different except purely by convention.
When you are doing instance methods of classes, you are free to call the 'self' parameter 'smurf', 'shelf' 'elf' and anything else that isn't a reserved word, but you will confuse people if you do so.

So '__main__' is the value that you will see for __name__ in a particular module when it is being run as the top-level whatever, but main/Main/Mein/Maine/mane I think isn't special except to limit confusion by other developers.  In the samples I made I kept spelling it stupid ways like that to remind myself of the point.
 
Stephan van Hulst
Saloon Keeper
Posts: 12992
281
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:So code in main function is gaurded but so is the code inside my_function function.


I don't think it makes sense to refer to function definitions as "guarded". Python users refer to code outside of function definitions as guarded or unguarded. In your example, the call to main() is guarded. If you remove the if-statement, the call is unguarded. It doesn't make sense to say that the function definitions themselves are guarded or unguarded.

Anyway, they entire point we're trying to make is that main() is NOT special and Python treats it exactly the same as any other function.

The reason main() doesn't execute in your second example is because __name__ doesn't contain the value '__main__', but instead it contains the value 'Test'.

'__main__' is a special value that gets assigned to __name__ when a script is executed as the entry point of the application, but there's nothing stopping you from executing a different function than main():
 
Tim Holloway
Saloon Keeper
Posts: 23692
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:

Mike Simmons wrote:People often write their code so that there is a method named main that is executed first, or at least early on.  



By making sure that it is at the top most in the code ? (Since python executes top to bottom)



The call to main goes at the bottom because statements put below the call to the main method won't be executed until after the call to the main method returns.

Since most extra-definitional code is involved in setting up data that is global to the file it's in and you don't want main() to execute until that data has been set up, you put the call to main() last. The definition of the main method can go anywhere.

Now whether you should even have global data is an entirely different debate. Although since Python lacks an explicit manifest constant definition, the need is somewhat greater than if you had variables at global scope.
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Does it mean that the only significance of the optional main function is that this code will be executed only when the script is executed (not imported) and the order in which main will be executed is where it comes in the top to bottom sequence ?
 
Jesse Silverman
Ranch Foreman
Posts: 415
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:Does it mean that the only significance of the optional main function is that this code will be executed only when the script is executed (not imported) and the order in which main will be executed is where it comes in the top to bottom sequence ?



Yes and no.

Any/all functions, regardless of name will only be called when the script is executed (not imported) if they are protected by the
if __name__ == '__main__'
construct.

They will all be executed where they come in the calling sequence, possibly modified by loops, if/elif, etc.

All function definitions must be seen/parsed before they are called, regardless of name, either inline in the file or via. an import statement.
 
Tim Holloway
Saloon Keeper
Posts: 23692
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:
All function definitions must be seen/parsed before they are called, regardless of name, either inline in the file or via. an import statement.



Repeating myself, Python is a:
linear language first
Procedural language second
Object-oriented language third.

A Python program can have all linear code and no functions or classes and still run. The reverse is not true, because linear code is what runs the top-level application logic.

There is no magic "main" function. Simply the fact that when you execute a Python file, the infrastructure variable "__main__" will be set true by by the Python run controller for the file you named on the Python command line. If that file invokes code in other Python files, the value of __main__ for code running in those files is false.

You do not need a main method. It's jusr a convenience and it's often simply used to make a python file runnable as a stand-alone test program.

 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the below code :



I think the difference between main and my_function is that:

main function will run when script is executed whereas my_function will never be executed. Is this the correct difference?
 
Jesse Silverman
Ranch Foreman
Posts: 415
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes.  Note, switching their names will mean main() never gets executed instead.  There is nothing magic about the name except convention.
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:Yes.  Note, switching their names will mean main() never gets executed instead.  There is nothing magic about the name except convention.



I believe magic is instead only in this part

 
Tim Holloway
Saloon Keeper
Posts: 23692
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Monica Shiralkar wrote:

Jesse Silverman wrote:Yes.  Note, switching their names will mean main() never gets executed instead.  There is nothing magic about the name except convention.



I believe magic is instead only in this part

Quite so. Python never executes any function or method by itself, only when linear code calls the function or method. Or when then function/method is called by a function/method further up the call stack. But the root of the call stack is linear code, not a function.

The variable __name__ is merely a property set by Python and it can execute nothing on its own.
 
Monica Shiralkar
Ranch Hand
Posts: 2449
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic