Nested function scope problem
Gabriel Genellina
gagsl-py at yahoo.com.ar
Wed Aug 9 22:55:35 EDT 2006
At Wednesday 9/8/2006 16:15, enigmadude at rock.com wrote:
>I agree with the previous comments that this approach is "bad form".
>But if you absolutely *must* modify an enclosing function's variables
>with an inner function, all you need to do is remember that a Python
>function is an object too, so it can be assigned attributes. ;-)
>
>def outer():
> outer.x = 1
> print outer.x
>
> def inner():
> outer.x = 2
>
> inner()
> print outer.x
I see two problems:
- Concurrency: two or more threads executing the same function,
writing to this "global"
- Can't be used (easily) on methods
On the original question, I would inherit from list:
> def addTok():
> if len(tok) > 0:
> ls.append(tok)
> tok = ''
>
>
class mylist(list)
def addTok(self, tok):
if len(tok)>0:
self.append(tok)
tok = ''
return tok
ls = mylist()
and use: tok = ls.addTok(tok) whenever the original code says addTok(tok)
Gabriel Genellina
Softlab SRL
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
More information about the Python-list
mailing list