reload()'ing modules and how it affects references

Igor V. Rafienko igorr at ifi.uio.no
Mon Jun 26 15:43:52 EDT 2000


[the article is a little bit long -- sorry]

Hi,


I'm trying to understand how reload() works. "Learning Python" and
Python's documentation warn against the dangers of combining 
from ... import ... and reload(), so that is fine, I use 
"import modulename".

What is rather pecular is that when I store a reference to a class (or
a class instance, for that matter), it does not get updated when I
reload() the entire module again:

# fooclass.Foo.Y is printed, runtime1.py import's fooclass
$ ./runtime1.py 
5 ; 5
			# here, I've changed fooclass.Foo.Y to 6 in emacs
reload( fooclass )
5 ; 5
5 ; 5
			# now re-assign the element explicitly
ml[0] = fooclass.Foo
6 ; 5
6 ; 5
			# and the instance
ml[1] = fooclass.Foo()
6 ; 6
6 ; 6


The Python code looks like this:

import sys
import fooclass

ml = [ fooclass.Foo, fooclass.Foo() ]
while 1:
    print ml[0].Y, ";", ml[1].Y
    next = sys.stdin.readline()
    if not next: break
    else:
        exec next
    print ml[0].Y, ";", ml[1].Y
# end while


(Apparently it does not matter whether the class reference/class
instance reference is stored in a variable or a list)

Now, for the questions:

1) What is the most elegant way of assigning all references to a
certain class to a new definition of this class after a reload? (I can
keep a dictionary/list of all the references, and assign them
explicitly right after the reload() call, but it just looks too ugly).

I suppose that it is impossible to make an instance of a class
suddenly "become" an instance of the new definition of the same class,
so that is fine.

2) When I call a method in class Foo that looks something like this:

def __repr__( self ):
    print <In Foo: Foo.Y ==", Foo.Y, "; self.Y == ", self.Y, ">"


after a reload the changes to Foo.Y affect Foo.Y but _not_ self.Y.
That is, the output from the test similar to the one above looks like
this (the function I call is __repr__):

$ ./runtime1.py 
6 ; 6 ; <Foo instance: self.x == 3, Foo.Y == 6, self.Y == 6>
reload( fooclass )    
	# now Foo.Y == 5 in the module file
6 ; 6 ; <Foo instance: self.x == 3, Foo.Y == 5, self.Y == 6>
6 ; 6 ; <Foo instance: self.x == 3, Foo.Y == 5, self.Y == 6>


Why does it happen -- I thought that Foo.Y and self.Y were supposed to
refer to the same object from within a class method? Am I missing
something essential?


tia and very willing to rtfm


ivr
-- 
Simula-konsulent? Simsulent? "I eat Java for breakfast!".
                                           -- thorkild



More information about the Python-list mailing list