GaryO
GaryO

Reputation: 6338

importing variable from module in python makes copy?

It seems like doing from foo import i makes a copy of i rather than importing i into the current namespace. Is that possible?

foo.py:

i=0

bar.py:

import foo
from foo import i

foo.i = 999

print i
print foo.i

This prints:

0
999

but I expected it them both to be 999 (just aliases for the same memory as it were). What am I missing?

Upvotes: 1

Views: 662

Answers (1)

Bakuriu
Bakuriu

Reputation: 102039

just aliases for the same memory as it were

You misunderstood how "variables" work in python. Variables are not memory locations. They are just names attached to objects. When you perform the assignment:

i = 0

you are giving the name i to a new object 0 in the current scope.

You should read the documentation about naming and binding


Maybe a diagram can make this clearer:

Situations before modifying i:

foo.i       i
  |        /
  |       /
  |      /
  |     /
  |    /
  |   /
  |  /
+-----+
| 999 |
+-----+

The object 999 has two references. When you do:

i = 0

This is what happens:

foo.i         i
  |           |
  |           |
  |           |
  |           |
  |           |
  |           |
  |           |
+-----+     +---+
| 999 |     | 0 |
+-----+     +---+

If you want to modify the value of the 999 object... well: you can't because in python integers are immutable.

Note that it doesn't have to do with scopes:

i = 999
j = i
i = 0
print(i, j)  # prints: 0 999

The names i and j are just labels to objects. If you come from C you may think of every python variable as a pointer to the actual object. As if the above code was:

int *i = &999;
int *j = i;
i = &0;
printf("%d %d", *i, *j);

Upvotes: 5

Related Questions