'from ... import *' woes...

Remco Gerlich scarblac at pino.selwerd.nl
Fri May 11 15:38:50 CEST 2001


Michael Lauer wrote in comp.lang.python:
> Ok, this is what I did expect. Now please see what happens if I use from ... import *
> 
> -------------------------------------------
> Python 2.1 (#1, Apr 21 2001, 03:38:10)
> [GCC 2.95.2 19991024 (release)] on linux2
> Type "copyright", "credits" or "license" for more information.
> >>> from stack import *
> >>> Stack
> []
> >>> push("Hallo")
> >>> Stack
> []
> >>> pop()
> 'Hallo'
> >>> 
> --------------------------------------------
> 
> 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... ?

When you do "from Stack import *", a local variable "Stack" is created that
refers to the same list as stack.Stack does.

Then when you push something, the function push (which comes from the module
stack), makes stack.Stack refer to a *new* list (namely the result of [data]
+ Stack). But the local reference isn't changed! So the local Stack variable
always refers to the old, empty list, but the functions pop and push make a
new one in stack.Stack all the time.

Moral of the story: always use a normal import unless you know *exactly*
what you're doing. In which case you wouldn't be asking the question :).

Read Fredrik Lundh's explanation at
http://effbot.org/guides/import-confusion.htm

Also, using a global is bad style (what if you want to use two stacks?) and
it'd be easier to use that .append() and .pop() methods of lists. But that's
not the point of this post :)

-- 
Remco Gerlich



More information about the Python-list mailing list