from xx import yy

Bob van der Poel bob at mellowood.ca
Fri Nov 17 12:26:45 EST 2017


On Thu, Nov 16, 2017 at 2:46 PM, Cameron Simpson <cs at cskk.id.au> wrote:

> On 16Nov2017 09:42, bvdp <bob at mellowood.ca> wrote:
>
>> In my original case, I think (!!!), the problem was that I had a variable
>> in mod1.py and when I did the "from mod1 import myvarible" all was fine.
>> Python create a new local-to-the-module variable and initialized it to the
>> value it was set to in mod1. And at this point all is well. But, when mod1
>> changed the value of myvariable the change didn't get passed to the other
>> modules. Of course, the reason for my confusion is that I'm thinking that
>> python is using pointers :) Opps.
>>
>> Maybe we need pointers in python <ducking>.
>>
>
> Thinking about this as pointers works pretty well. We call them references
> in Python because they are not (or need not be) memory addresses and C
> pointers are memory addresses. However the model is the same: an arrow from
> a variable name pointing at the place a value (the object) is stored.
>
> Look:
>
>  mod1.py: x = 1
>
> making:
>
>  mod1.x --> 1
>
> Now consider:
>
>  mod2.py: from mod1 import x
>
> Making:
>
>  mod1.x --> 1
>             ^
>  mod2.x ----+
>
> both referring to the "1" object.
>
> Now:
>  mod2.py: x = 2
>
> Making:
>
>  mod1.x --> 1
>  mod2.x --> 2
>
> You see that mod1 is not adjusted. Versus:
>
>  mod2.py: import mod1
>
> Making:
>
>  mod2.mod1 --> mod1, mod1.x --> 1
>
> Then:
>
>  mod2.py: mod1.x = 2
>
> Making:
>
>  mod2.mod1 --> mod1, mod1.x --> 2
>
> Because you're adjusting the reference "mod1.x", _not_ the distinct
> reference "mod2.x".
>
> Cheers,
> Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)
>
> Draw little boxes with arrows.  It helps.       - Michael J. Eager
>

Yes, your examples work perfectly. It's when one does an "from mod1 import
var" that it doesn't.

In mod1 set var to a value. Lets use 5.

Now, in mod2 we do:

  from mod1 import var

And, yes, var is equal to 5. But, to the folks like me who are not complete
pythonistas, we'd think it worked and was wonderful.

But, if we change the variable in mod1 whit a function in mod1, the value
doesn't change in mod2. The problem is that from/import does not create var
as a pointer, but as a new variable.



-- 

**** Listen to my FREE CD at http://www.mellowood.ca/music/cedars ****
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bob at mellowood.ca
WWW:   http://www.mellowood.ca



More information about the Python-list mailing list