[Tutor] scoping issues

Terry Carroll carroll@tjc.com
Tue May 6 15:04:03 2003


I have a module I'm writing.  One method in it maintains a list, call it 
mylist.

I want to set it up so that, if the method is never called, mylist is an
empty list.  If it's called, it gets set to the results from that call.

This is easy:

mylist = []

def meth():
    mylist.append('a')
    mylist.append('b')
    mylist.append('c')


The problem is, I want to re-set mylist on each call to meth() so that it 
only has the things from the last call.  If I call this twice, I get:

 before first call:
 []
 after first call:
 ['a', 'b', 'c']
 after second call:
 ['a', 'b', 'c', 'a', 'b', 'c']

The first two are what I want, the last isn't.

I tried resetting mylist back to [] in meth():

 before first call:
 []
 after first call:
 []
 after second call:
 []

Well, that's no good.  I'm sure everything in meth() is working, but now
(and I'm not sure I fully understand this)  there seem to be two "mylist"
variables, modulename.mylist and another that I'm not sure how to even
access.

So, how can I achieve my goal here?  How can I "reset" mylist to a null 
list in each invocation of the method?

-- 
Terry Carroll        |  "To have this rare opportunity
Santa Clara, CA      |    is a rare opportunity."
carroll@tjc.com      |    - Houston Rockets' Yao Ming, on being named
Modell delendus est  |    starting center for the 2003 NBA All-Star Game