imported var not being updated
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Tue Mar 9 09:48:59 EST 2010
John Posner a écrit :
> On 3/8/2010 11:55 PM, Gary Herron wrote:
> <snip>
>>
>> The form of import you are using
>> from helpers import mostRecent
>> makes a *new* binding to the value in the module that's doing the
>> import.
>
> <snip>
>
>> What you can do, is not make a separate binding, but reach into the
>> helpers module to get the value there. Like this:
>>
>> import helpers
>> print helpers.mostRecent
>>
>
> Gary, are you asserting that in these separate situations:
>
> one.py:
>
> from helpers import mostRecent
> x = mostRecent
>
> two.py:
>
> import helpers
> x = helpers.mostRecent
>
>
> ... the name "x" will be bound to different objects?
Nope. What he's saying is that one.x and two.x are two different names -
each living in it's own namespace - that happen to be bound to the same
object. Now rebiding one.x to a different object will _of course_ have
no impact on the object two.x is bound to.
That's exactly the same as:
one = dict()
two = dict()
# one['x'] and two['x'] refer to the same object
one['x'] = two['x'] = ["foo", "bar"]
print one['x'], two['x'], one['x'] is two['x']
# mutating one['x'], visible in two['x']
# (of course since it's the same object)
one['x'].append("baaz")
print one['x'], two['x'], one['x'] is two['x']
# now rebind one['x']
one['x'] = 42
# obvious result: one['x'] and two['x'] now refer to 2 different objects
print one['x'], two['x'], one['x'] is two['x']
If in doubt about namespaces, think dicts. Namespaces are like dicts -
and are often nothing else that a plain old dict FWIW.
HTH
More information about the Python-list
mailing list