Attachment 'oldnames.py'

Download

   1 """
   2 Domenstrate how old names remain in reloaded modules
   3 """
   4 
   5 import imp
   6 import sys
   7 import os
   8 
   9 module_name = 'test_module'
  10 
  11 def make_module(name, dict):
  12     """ test helper - create module from keywords """
  13     module = file(name + '.py', 'w')
  14     for key, value in dict.items():
  15         module.write('%s = %s\n' % (key, repr(value)))
  16     module.close()
  17     
  18     # Rmove old pyc
  19     pyc = name + '.pyc'
  20     if os.path.exists(pyc):
  21         os.remove(pyc)
  22 
  23 def import_module(name):
  24     """ load module or return the cached module """
  25     try:
  26         return sys.modules[name]
  27     except KeyError:
  28         return load_module(name)
  29 
  30 def load_module(name):
  31     """ Load module, reloading if it was allready imported """
  32     fp, pathname, description = imp.find_module(name)
  33     try:
  34         module = imp.load_module(name, fp, pathname, description)
  35     finally:
  36         if fp: fp.close()
  37     return module
  38 
  39 # Create a module on disk and import
  40 make_module(module_name, {'name': 'nir'})
  41 module = import_module(module_name)
  42 assert module.name == 'nir'
  43 
  44 # Change a value in the module and reload
  45 make_module(module_name, {'name': 'naomi'})
  46 module = load_module(module_name)
  47 assert module.name == 'naomi'
  48 
  49 # Add a name the module and reload
  50 make_module(module_name, {'name': 'naomi', 'age': 4})
  51 module = load_module(module_name)
  52 assert module.age == 4
  53 
  54 # Remove a name from the module and reload
  55 # Old names remain in the module
  56 make_module(module_name, {'name': 'nir'})
  57 module = load_module(module_name)
  58 assert module.age == 4

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2004-08-22 11:13:48, 1.5 KB) [[attachment:oldnames.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.