Is it possible to create C-style "main" function in Python? (for teaching purposes)

Dave Angel davea at ieee.org
Mon Oct 3 15:14:13 EDT 2011


On 01/-10/-28163 02:59 PM, Aivar Annamaa wrote:
> Hi!
>
> I'm looking for a trick or hidden feature to make Python 3 automatically
> call a "main" function but without programmers writing `if __name__ ==
> "__main__": ...`
>
> I found rejected PEP 299, but i thought that maybe there's something new
> already.
>
> Here's why I want such a thing:
> I'm teaching introductory programming course with Python. I've seen that
> global variables attract beginners like honey attracts bees and this makes
> teaching function parameters harder. When students learn functions, they
> usually write their function definitions and function applications in the
> same scope -- in top-level of the module (don't know the correct term for
> it). This has the downside, that any variable introduced in top-level is
> automatically visible in function definitions and I have hard time
> convincing students not to use those variables in functions directly.
>
> I've been thinking that it might be better for teaching if all program code
> would be in functions. This would make "Hello World" a bit more difficult,
> but would help teaching the "real thing" ie. functions.
>
> best regards,
> Aivar
>
It's not clear if you're asking for a new fork of the language, or just 
wanting to keep people from bad habits.

Like it or not, there are plenty of globals already there, one of them 
being __name__ .  All the built-ins are effectively global, and so
  is any function they define at top-level.  Likewise any top-level 
class, and any symbols imported with import or with from/import.  So I 
consider it impractical for the language to do something that 
self-discipline is required for.

Is it explaining the if statement that's the problem?  If so, you could 
have them do an unconditional main(sys.argv) at the bottom of their 
file, and not bother putting an if statement in front of it.  Then when 
you get to user-written modules, you could introduce the if __name__ and 
explain its need.

DaveA







More information about the Python-list mailing list