On Fri, 09 Mar 2007 11:18:47 -0500, Lou Pecora
<> declaimed the following in comp.lang.python:
> A further confusion (if I may):
>
> I have noticed that using from xxx import * can lead to problems when
> trying to access variables in the xxx module.
>
For the most part, the recommendation is to /never/ user "from <>
import *" (the exceptions tend to be things like predefined constants
for GUI libraries, which often have names that make them unique, and as
constants one isn't supposed to be changing them).
> E.g.
>
> -- File f2.py
>
> imvar=1
>
> def prn():
> print imvar
>
> -- File junk.py
>
> from f2 import *
> prn()
> imvar=2
> prn()
>
> -- Running junk.py gives the output:
>
> 1
> 1
>
> Not what I would expect which is,
>
> 1
> 2
>
> Namespaces get confusing. I have begun to switch to using 'import f2
> as' which gives the 2nd expected result. Safer, but still a bit puzzling.
>
Expected behavior if you 1) understand how Python variable binding
works, and 2) that "from <> import *" is equivalent to
import <>
name1 = <>.name1
name2 = <>.name2
IOWs, one is creating local names that are bound to the objects
inside the imported module. If, subsequently, one does
name2 = 123
one has UNbound the connection to <>.name2 and rebound the local name to
the integer object 123. Whereas
<>.name2 = 123
says "go into the module <>, and rebind its 'name2' to the integer
object 123"; since you "went inside" to do the rebinding, any other code
that also uses the <>.name2 reference will see the change inside <>.
A bare name "assignment" always causes a rebinding of that name. A
qualified assignment (module, list, dictionary, class instance) "goes
inside" the top level item to rebind the item inside it:
module.object = xxx #rebinds name "object" inside module
list[element] = xxx #rebinds the indexed element inside the list
dict[key] = xxx #rebinds the indexed (by key) element
instance.attr = xxx #rebinds the attribute inside the instance
--
Wulfraed Dennis Lee Bieber KD6MOG
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff:
web-)
HTTP://www.bestiaria.com/