[Tutor] packages,modules, and module attributes
Alan Gauld
alan.gauld at freenet.co.uk
Wed Oct 26 19:32:47 CEST 2005
> I've a question, essentially about the import statement. Suppose I have
> two python files, a.py and b.py:
OK, I'll have a go although I'm only 90% sure I've got it right...
> a.py
> ----
> flag = True
>
> def getFlag():
> return flag
>
> b.py
> ----
> from a import *
This imports the names from a.
Thus b now has a name flag that points to TRue and a name
getFlag that points to the function in a.
> now, in the interpreter:
>
>>>> import b
>>>> b.flag
> True
>>>> b.flag=False
>>>> b.flag
> False
This first reads the value imported from a then creates a new name
in b that overwrites the imported value and sets it to False.
>>>> b.getFlag()
> True
This calls the function in a which returns the value from a which is
still set to True.
> this is probably related to namespaces? I find it very confusing,
It is to do with namespaces and shows why two bad practices you have
used are indeed bad practices! :-)
First if you had used
import a
in b instead of
from a import *
All would have worked as you expected because you would have
been forced to specify
b.a.flag
etc.
Secondly relying on a global variable in the function getFlag meant that
when you imported getFLag the function object remained in a and
accessed the variable flag in a. If you had passed the name of the flag
to getFlag as a parameter then it would have worked as expected
- although only returning the value you already had! (But if Flag were
a more complex object it would then make sense!)
So as usual the advice "do not use from X import *" holds.
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list