Maintaining a list

Aahz aahz at pythoncraft.com
Sat Feb 14 10:27:27 EST 2004


In article <b4a8ffb6.0402131633.1cb220d6 at posting.google.com>,
Thomas Philips <tkpmep at hotmail.com> wrote:
>
>The list must be initialized to an empty list before the first call,
>and must be preserved between calls. I have not got to object oriented
>programming as yet, so please keep the solution simple.

Unfortunately, while the other solutions given fit your technical
requirements, they're also what I (and probably others) would consider
unnatural for Python programs.  That's partly because abuse of default
parameters and closures are actually two of the more difficult concepts
for people to learn correctly, IME.  Here's a "less-simple" solution that
does what you want in a Pythonic fashion, though it still uses a trick:

>>> class CallableList:
...     def __init__(self):
...         self.data = []
...     def __call__(self, x):
...         self.data.append(x)
...         return self.data
...
>>> myroutine = CallableList()
>>> myroutine('1')
['1']
>>> myroutine('spam')
['1', 'spam']
>>> myroutine.data
['1', 'spam']
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach



More information about the Python-list mailing list