'from ... import *' woes...
Fredrik Lundh
fredrik at pythonware.com
Fri May 11 04:01:54 EDT 2001
Michael Lauer wrote:
> I have a strange problem...
>
> Consider the following program which implements a stack:
>
> -------------------------------
> #!/usr/bin/env python
> Stack = []
>
> def push(data):
> global Stack
> Stack = [data] + Stack
>
>
> def pop():
> global Stack
> top, Stack = Stack[0], Stack[1:]
> return top
> ------------------------------
that's about the worst way you can implement a stack in
Python, but I hope you already knew that...
> So... what is happening here ? Why is the Stack display as an empty list although
> a value is 'pushed' and I can 'pop' that value... ?
variables != objects
assignment in python doesn't modify objects, it rebinds variable
names. in this case, your push and pop functions rebind their
global (i.e. module-level) Stack variable for each operation [1]
when you use import, you look it up in the stack module's name-
space for each access, so you'll see the same thing as the functions
inside the stack module.
when you use from-import, Python creates a local variable pointing
to the current value of the list object [2]. when push and pop re-
binds the variable, you still have a reference to the original object.
Cheers /F
1) more here: http://effbot.org/guides/python-objects.htm
2) more here: http://effbot.org/guides/import-confusion.htm
More information about the Python-list
mailing list