The Difference between Import and From??
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Tue Mar 14 20:55:10 EST 2000
Akira Kiyomiya wrote in comp.lang.python:
> Well, I have a simple question that I cannot wait to ask. So here you go.
> It should be simple.
I've added some translations into English. Maybe it'll be easier that way.
> % cat small.py
> x = 1
> y = [1, 2]
>
> % python
> >>> from small import x, y
Local name 'x' points to the integer 1 from module small
Local name 'y' points to the list [1, 2] from module small
> >>> x = 42
Local name 'x' now points to the integer 42
> >>> y[0] = 42
The list that y points to is changed, so that its first element is 42.
(note: y still points to the same list)
> >>> import small
Local name 'small' points to the module "small".
> >>> small.x
> 1 # why? I tought it would be 42?
Module small's x was never changed. Local name 'x' came to point to 42,
but that has nothing to do with small's x.
> >>> small.y
> [42 ,2] # yeah, I thought so.
Small.y still points to the same list as y does. *That list was changed*.
Therefore, small.y is also changed.
> I have a feeling that I am confused of how Python imports a file. Maybe
> the difference between import and from??
You don't grok it completely, but it's more complex than that. It has to do
with mutable and immutabe objects as well. I managed to understand this
after reading Learning Python, but maybe you don't have that book or you
don't understand it yet. Anyway, I can't really explain it as an answer to
this question.
I see that I describe variables as "pointing to" an object. That's influence
from other languages. Every Python variable acts like a pointer would in C
or Pascal.
--
Remco Gerlich, scarblac at pino.selwerd.nl
3:53am up 8 days, 16:14, 8 users, load average: 0.08, 0.05, 0.03
More information about the Python-list
mailing list