Sharing package data across files

Steven D'Aprano steve at pearwood.info
Tue Jun 28 20:27:10 EDT 2016


On Wed, 29 Jun 2016 08:07 am, John Pote wrote:

>> from foo import bar
>> bar = "oranges"
>>
>> No code outside of a will see bar as "oranges" because my setting of bar
>> merely affected the name "bar" inside module a, it did not "reach into"
>> the foo module object and update its "bar".

zackbaker at gmail.com's description above is correct.

> Correct me if I'm wrong but is not the above only true if bar has been
> assigned to and thus references an imutable object? In your example the
> string "oranges".

No, assignment and importing doesn't know the difference between immutable
and mutable objects. Importing works the same way for strings and it does
for lists.

However, this part is correct:

> If bar has been assigned to a mutable object in module foo then every
> module importing via "from foo import bar" will all import the name bar
> pointing to the same mutable object. If this mutable obj is changed via
> bar in one module then every other module importing bar will also see
> the change.

That's right. Think of it this way:

- every module has their own unique NAME "bar", so when a module assigns to
bar using `bar = something`, it is only changing the name in its own
namespace, it's not reaching into any other namespace;

- but there's only one OBJECT being imported, so if that object is mutable,
and you mutate it, all modules see the same change in state.

In other words, importing does not copy objects, it just creates a new name,
in the current namespace, that is bound to that object.

If it helps you to think about the underlying C implementation, you can
think about pointers to objects:

In foo, you have bar pointing to some object:

    bar ---> OBJ


"from foo import bar" creates a new local variable which likewise points to
the same OBJ (no copy is made):

    foo.bar ---> OBJ
                  ^
                  |
    a.bar --------+


Assignment changes the pointer, not the thing pointed to:

    foo.bar ---> OBJ
    a.bar --------------> "oranges"




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list