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

Alan Meyer ameyer2 at yahoo.com
Tue Oct 4 21:07:10 EDT 2011


On 10/3/2011 12:26 PM, Alec Taylor wrote:
...
> On Tue, Oct 4, 2011 at 3:21 AM, Aivar Annamaa<aivar.annamaa at gmail.com>  wrote:
...
>> 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__": ...`
...
>> 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. ...

Teaching good programming practice is hard.  Many programmers, not just 
students, take the attitude, "My code works.  Who cares what it looks 
like?"  Getting them to understand that code has to be readable, 
understandable, and maintainable can be very hard.

I wonder if some teaching exercises would help, for example:

1. Find a program, perhaps submitted by a student in a previous class or 
perhaps something you write yourself, that's full of global variables. 
Assign the students to rewrite the program so that it has no globals at 
all, and to write up a comparison of the pros and cons of the global and 
no-global approaches.

2. Find or write a program with lots of globals.  Introduce some subtle 
bugs into the program that have to do with global references.  Assign 
the students to a) find and fix the bugs and b) explain how the code 
could have been written to prevent bugs like this from creeping in.

3. Find or write a program with a number of globals.  For each global, 
ask the students to write an analysis comparing its usefulness and/or 
dangerousness.  Are some of the globals worse than others?  Why?

4. Find or write a program with some globals.  Make up a change request 
from a user that will run into problems because of the globals.  Assign 
the students to implement the change request.

There are probably lots of other similar exercises one could make up.

The idea is not to force students to do the right thing, but to get them 
to understand the differences between the better ways and the worse ways 
to write code.

Incidentally, all of these exercises involve maintaining or re-writing 
existing code written by other people.  Students don't usually do much 
of that, but when they get a real job, they find that maintenance is 
most of what they actually do, especially as junior programmers.  Having 
to work in the real world of maintaining other people's code gives a 
student a better appreciation of the value of clean, modular, readable, 
documented code.

     Alan



More information about the Python-list mailing list