This commit was manufactured by cvs2svn to create tag 'r221c2'.
[python/dscho.git] / Lib / encodings / __init__.py
blob3830954d16c79ea78a4d4935db6b4f9701ab5fe2
1 """ Standard "encodings" Package
3 Standard Python encoding modules are stored in this package
4 directory.
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'.
10 Each codec module must export the following interface:
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.
16 In addition, a module may optionally also define the following
17 APIs which are then used by the package's codec search function:
19 * getaliases() -> sequence of encoding name strings to use as aliases
21 Alias names returned by getaliases() must be standard encoding
22 names as defined above (lower-case, hyphens converted to
23 underscores).
25 Written by Marc-Andre Lemburg (mal@lemburg.com).
27 (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
29 """#"
31 import codecs,aliases,exceptions
33 _cache = {}
34 _unknown = '--unknown--'
36 class CodecRegistryError(exceptions.LookupError,
37 exceptions.SystemError):
38 pass
40 def search_function(encoding):
42 # Cache lookup
43 entry = _cache.get(encoding,_unknown)
44 if entry is not _unknown:
45 return entry
47 # Import the module
48 modname = encoding.replace('-', '_')
49 modname = aliases.aliases.get(modname,modname)
50 try:
51 mod = __import__(modname,globals(),locals(),'*')
52 except ImportError,why:
53 # cache misses
54 _cache[encoding] = None
55 return None
57 # Now ask the module for the registry entry
58 try:
59 entry = tuple(mod.getregentry())
60 except AttributeError:
61 entry = ()
62 if len(entry) != 4:
63 raise CodecRegistryError,\
64 'module "%s" (%s) failed to register' % \
65 (mod.__name__, mod.__file__)
66 for obj in entry:
67 if not callable(obj):
68 raise CodecRegistryError,\
69 'incompatible codecs in module "%s" (%s)' % \
70 (mod.__name__, mod.__file__)
72 # Cache the codec registry entry
73 _cache[encoding] = entry
75 # Register its aliases (without overwriting previously registered
76 # aliases)
77 try:
78 codecaliases = mod.getaliases()
79 except AttributeError:
80 pass
81 else:
82 for alias in codecaliases:
83 if not aliases.aliases.has_key(alias):
84 aliases.aliases[alias] = modname
86 # Return the registry entry
87 return entry
89 # Register the search_function in the Python codec registry
90 codecs.register(search_function)