Exception handling with NameError

Peter Otten __peter__ at web.de
Sat Nov 6 06:32:24 EDT 2010


Zeynel wrote:

> On Nov 5, 1:26 pm, Peter Otten <__pete... at web.de> wrote:
> 
>> Of course I'm only guessing because you don't provide enough context.
>>
>> Peter
> 
> Thanks.
> 
> This is the problem I am having, in general:
> 
> K = []  # a container list
> K = ["A", "B"]
> 
> ARCHIVE = [] # a list where items from K is archived
> 
> ARCHIVE.append(K)
> 
> # K is updated
> K = ["C", "D"]
> 
> # append new K to ARCHIVE
> ARCHIVE.append(K)
> 
> The problem I am having is this: If I do:
> 
> K = []
> ARCHIVE = []
> ARCHIVE.append(K)
> 
> any time K is updated (user submits new input) the content of ARCHIVE
> is erased:
> 
> If I do this:
> 
> K = []
> ARCHIVE.append(K)
> 
> I get NameError: "Name ARCHIVE not defined"
> 
> What is the solution?

archive = []
k = ["a", "b"]
for new_k in get_container():
    archive.append(k)
    k = new_k

I. e. don't rebind the name archive if you don't want to lose old data.

>>> import random, string
>>> def get_container():
...     for i in range(5):
...             yield [random.choice(string.ascii_lowercase) for _ in 
range(2)]
...
>>> archive = []
>>> k = ["a", "b"]
>>> for new_k in get_container():
...     archive.append(k)
...     k = new_k
...     print "k is now", k
...     print "archive contents", archive
...
k is now ['h', 'r']
archive contents [['a', 'b']]
k is now ['t', 'y']
archive contents [['a', 'b'], ['h', 'r']]
k is now ['y', 'q']
archive contents [['a', 'b'], ['h', 'r'], ['t', 'y']]
k is now ['p', 'i']
archive contents [['a', 'b'], ['h', 'r'], ['t', 'y'], ['y', 'q']]
k is now ['y', 'n']
archive contents [['a', 'b'], ['h', 'r'], ['t', 'y'], ['y', 'q'], ['p', 
'i']]

Peter




More information about the Python-list mailing list