home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Lib / Python2.0 / encodings / __init__.py next >
Encoding:
Python Source  |  2000-10-25  |  2.2 KB  |  79 lines

  1. """ Standard "encodings" Package
  2.  
  3.     Standard Python encoding modules are stored in this package
  4.     directory.
  5.  
  6.     Codec modules must have names corresponding to standard lower-case
  7.     encoding names with hyphens mapped to underscores, e.g. 'utf-8' is
  8.     implemented by the module 'utf_8.py'.
  9.  
  10.     Each codec module must export the following interface:
  11.  
  12.     * getregentry() -> (encoder, decoder, stream_reader, stream_writer)
  13.     The getregentry() API must return callable objects which adhere to
  14.     the Python Codec Interface Standard.
  15.  
  16.     In addition, a module may optionally also define the following
  17.     APIs which are then used by the package's codec search function:
  18.  
  19.     * getaliases() -> sequence of encoding name strings to use as aliases
  20.  
  21.     Alias names returned by getaliases() must be lower-case.
  22.  
  23.  
  24. Written by Marc-Andre Lemburg (mal@lemburg.com).
  25.  
  26. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  27.  
  28. """#"
  29.  
  30. import codecs,aliases
  31.  
  32. _cache = {}
  33. _unknown = '--unknown--'
  34.  
  35. def search_function(encoding):
  36.     
  37.     # Cache lookup
  38.     entry = _cache.get(encoding,_unknown)
  39.     if entry is not _unknown:
  40.         return entry
  41.  
  42.     # Import the module
  43.     modname = encoding.replace('-', '_')
  44.     modname = aliases.aliases.get(modname,modname)
  45.     try:
  46.         mod = __import__(modname,globals(),locals(),'*')
  47.     except ImportError,why:
  48.         _cache[encoding] = None
  49.         return None
  50.     
  51.     # Now ask the module for the registry entry
  52.     try:
  53.         entry = tuple(mod.getregentry())
  54.     except AttributeError:
  55.         entry = ()
  56.     if len(entry) != 4:
  57.         raise SystemError,\
  58.               'module "%s.%s" failed to register' % \
  59.               (__name__,modname)
  60.     for obj in entry:
  61.         if not callable(obj):
  62.             raise SystemError,\
  63.                   'incompatible codecs in module "%s.%s"' % \
  64.                   (__name__,modname)
  65.  
  66.     # Cache the encoding and its aliases
  67.     _cache[encoding] = entry
  68.     try:
  69.         codecaliases = mod.getaliases()
  70.     except AttributeError:
  71.         pass
  72.     else:
  73.         for alias in codecaliases:
  74.             _cache[alias] = entry
  75.     return entry
  76.  
  77. # Register the search_function in the Python codec registry
  78. codecs.register(search_function)
  79.