help on "from deen import *" vs. "import deen"

Ned Batchelder ned at nedbatchelder.com
Mon Nov 14 17:33:26 EST 2016


On Sunday, November 13, 2016 at 9:39:12 PM UTC-5, jf... at ms4.hinet.net wrote:
> Running the following codes (deen.py) under Win32 python 3.4.4 terminal:
> 
> tbli = [0x66, 0x27, 0xD0]
> tblm = [0 for x in range(3)]
> def gpa(data):
>     td = data ^ tblm[2]
>     return td

The function gpa references the global tblm. Globals in Python are
global to the module (.py file) they appear in, and each module has
its own set of globals.  So the when the gpa function accesses tblm,
it's always going to be accessing the tblm in the deen module,
because gpa is defined in the deen module.


> 
> I can get a correct answer this way:
> >>> import deen
> >>> deen.tblm = deen.tbli
> >>> deen.gpa(0x7d)
> 173  # 0xad (= 0x7d ^ 0xd0) is decimal 173

Here you are updating deen.tblm, so when you call gpa, it sees the
new value you assigned to deen.tblm.

> 
> But I get a wrong answer this way:
> >>> from deen import *
> >>> tblm = tbli
> >>> gpa(0x7d)
> 125  # it's 0x7d, the tblm[2] is 0
> 
> Why? why! why:-(

Here you are assigning a value to your own tblm, not deen.tblm,
so gpa does not see the new value.

HTH,

--Ned.



More information about the Python-list mailing list