Reload() Confusion

David MacQuigg dmq at gain.com
Mon Mar 22 05:20:09 CET 2004


I like this code example because it gets the student to think about
how modules are kept in memory.  Showing the module's dictionary
before and after a reload is great.  I'll try to integrate it into my
presentation, perhaps in place of the second example, which can now
become an exercise.  Thanks.

-- Dave

On Sat, 20 Mar 2004 17:55:17 -0500, mwilson at the-wire.com (Mel Wilson)
wrote:

>For what it's worth, the following code:
>
>#=======================
>"""M1 version 1"""
>a=1
>b=2
>c=[1]
>d=[2]
>
>#=======================
>"""M1 version 2"""
>a=1
>b=4
>c=[3]
>e=[4]
>
>#=======================
>"""test_reload.py"""
>import os, shutil
>def module_contents (M):
>    print "Doc: ", M.__doc__
>    for k, v in M.__dict__.items():
>        if not k.startswith ("__"):
>            print "%s:\t%d\t%s" % (k, id(v), v)
>
>def grab_contents (M):
>    d = {}
>    for k, v in M.__dict__.items():
>        if not k.startswith ("__"):
>            d[k] = v
>    return d
>
>#os.remove ("M1.pyc")
>shutil.copyfile ("M1_1.py", "M1.py")
>import M1
>module_contents (M1)
>mc = grab_contents (M1)
>
>print
>os.remove ("M1.pyc")
>shutil.copyfile ("M1_2.py", "M1.py")
>reload (M1)
>module_contents (M1)
>
>print '\nMC:'
>for k, v in mc.items():
>    print "%s:\t%d\t%s" % (k, id(v), v)
>
>
>
>
>Which gives
>
>F:\home\mwilson\Projects\python\testscript>python test_reload.py
>Doc:  M1 version 1
>a:      8463376 1
>c:      9940432 [1]
>b:      8470496 2
>d:      9940368 [2]
>
>Doc:  M1 version 2
>a:      8463376 1
>c:      9940272 [3]
>b:      8468480 4
>e:      9937584 [4]
>d:      9940368 [2]
>
>MC:
>a:      8463376 1
>c:      9940432 [1]
>b:      8470496 2
>d:      9940368 [2]
>
>
>The second os.remove seems to be required in case the reloaded
>version of M1.py is older than the imported one.
>
>        Regards.        Mel.




More information about the Python-list mailing list