Odd import behavior

Facundo Batista facundo at taniquetil.com.ar
Tue Feb 27 07:09:43 EST 2007


Gregory Piñero wrote:

> I didn't realize Python behaved like this.  Is there an FAQ I can read on this?

I'll explain step by step:


> FILE module1.py:
> VAR1='HI'
>
> FILE MAIN.py:
> from module1 import *
> import module1

Here you have, in your module scope, a name 'VAR1' that points to "HI"
and a name 'module1' that points to a module where you have a name
'VAR1' that points to "HI" (and that's why you have to use two names
"import.VAR1")


> print VAR1
> print module1.VAR1

This prints "HI" (VAR1 pointed to it), and "HI" (VAR1, inside module1,
pointed to it).


> VAR1='bye'

This rebinds the name "VAR1" in this module scope. Now it points to
"bye", not pointing anymore to the (still living) string "HI". Take note
that you're not changing the value in memory, you're pointing to another
place.


> print VAR1
> print module1.VAR1

This prints "bye" (VAR1 now is pointing to it), and "HI" (VAR1, inside
module1, still is pointing to it).


> It seems to use module1.VAR1 for VAR1 until I assign something to VAR1
> in which case they become seperate.

You do not assign something to VAR1, you rebind the name to point a new
object in memory.

For further detail in the explanation, you can check this very, *very*
good paper (it's small and fun):

  http://starship.python.net/crew/mwh/hacks/objectthink.html

Regards.

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/






More information about the Python-list mailing list