blob: b71e4ca9bc2cd6cfbce51e0e51411a118b697c63 [file] [log] [blame]
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +00001=============================================================================
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +00002 Python Unicode Integration Proposal Version: 1.7
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +00003-----------------------------------------------------------------------------
4
5
6Introduction:
7-------------
8
9The idea of this proposal is to add native Unicode 3.0 support to
10Python in a way that makes use of Unicode strings as simple as
11possible without introducing too many pitfalls along the way.
12
13Since this goal is not easy to achieve -- strings being one of the
14most fundamental objects in Python --, we expect this proposal to
15undergo some significant refinements.
16
17Note that the current version of this proposal is still a bit unsorted
18due to the many different aspects of the Unicode-Python integration.
19
20The latest version of this document is always available at:
21
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +000022 http://starship.python.net/~lemburg/unicode-proposal.txt
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +000023
24Older versions are available as:
25
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +000026 http://starship.python.net/~lemburg/unicode-proposal-X.X.txt
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +000027
28
29Conventions:
30------------
31
32· In examples we use u = Unicode object and s = Python string
33
34· 'XXX' markings indicate points of discussion (PODs)
35
36
37General Remarks:
38----------------
39
40· Unicode encoding names should be lower case on output and
41 case-insensitive on input (they will be converted to lower case
42 by all APIs taking an encoding name as input).
43
Marc-André Lemburgbff879c2000-08-03 18:46:08 +000044· Encoding names should follow the name conventions as used by the
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +000045 Unicode Consortium: spaces are converted to hyphens, e.g. 'utf 16' is
46 written as 'utf-16'.
47
Marc-André Lemburgbff879c2000-08-03 18:46:08 +000048· Codec modules should use the same names, but with hyphens converted
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +000049 to underscores, e.g. utf_8, utf_16, iso_8859_1.
50
Marc-André Lemburgbff879c2000-08-03 18:46:08 +000051
52Unicode Default Encoding:
53-------------------------
54
55The Unicode implementation has to make some assumption about the
56encoding of 8-bit strings passed to it for coercion and about the
57encoding to as default for conversion of Unicode to strings when no
58specific encoding is given. This encoding is called <default encoding>
59throughout this text.
60
61For this, the implementation maintains a global which can be set in
62the site.py Python startup script. Subsequent changes are not
63possible. The <default encoding> can be set and queried using the
64two sys module APIs:
65
66 sys.setdefaultencoding(encoding)
67 --> Sets the <default encoding> used by the Unicode implementation.
68 encoding has to be an encoding which is supported by the Python
69 installation, otherwise, a LookupError is raised.
70
71 Note: This API is only available in site.py ! It is removed
72 from the sys module by site.py after usage.
73
74 sys.getdefaultencoding()
75 --> Returns the current <default encoding>.
76
77If not otherwise defined or set, the <default encoding> defaults to
78'ascii'. This encoding is also the startup default of Python (and in
79effect before site.py is executed).
80
81Note that the default site.py startup module contains disabled
82optional code which can set the <default encoding> according to the
83encoding defined by the current locale. The locale module is used to
84extract the encoding from the locale default settings defined by the
85OS environment (see locale.py). If the encoding cannot be determined,
86is unkown or unsupported, the code defaults to setting the <default
87encoding> to 'ascii'. To enable this code, edit the site.py file or
88place the appropriate code into the sitecustomize.py module of your
89Python installation.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +000090
91
92Unicode Constructors:
93---------------------
94
95Python should provide a built-in constructor for Unicode strings which
96is available through __builtins__:
97
98 u = unicode(encoded_string[,encoding=<default encoding>][,errors="strict"])
99
100 u = u'<unicode-escape encoded Python string>'
101
102 u = ur'<raw-unicode-escape encoded Python string>'
103
104With the 'unicode-escape' encoding being defined as:
105
106· all non-escape characters represent themselves as Unicode ordinal
107 (e.g. 'a' -> U+0061).
108
109· all existing defined Python escape sequences are interpreted as
110 Unicode ordinals; note that \xXXXX can represent all Unicode
111 ordinals, and \OOO (octal) can represent Unicode ordinals up to U+01FF.
112
113· a new escape sequence, \uXXXX, represents U+XXXX; it is a syntax
114 error to have fewer than 4 digits after \u.
115
116For an explanation of possible values for errors see the Codec section
117below.
118
119Examples:
120
121u'abc' -> U+0061 U+0062 U+0063
122u'\u1234' -> U+1234
123u'abc\u1234\n' -> U+0061 U+0062 U+0063 U+1234 U+005c
124
125The 'raw-unicode-escape' encoding is defined as follows:
126
127· \uXXXX sequence represent the U+XXXX Unicode character if and
128 only if the number of leading backslashes is odd
129
130· all other characters represent themselves as Unicode ordinal
131 (e.g. 'b' -> U+0062)
132
133
134Note that you should provide some hint to the encoding you used to
135write your programs as pragma line in one the first few comment lines
136of the source file (e.g. '# source file encoding: latin-1'). If you
137only use 7-bit ASCII then everything is fine and no such notice is
138needed, but if you include Latin-1 characters not defined in ASCII, it
139may well be worthwhile including a hint since people in other
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000140countries will want to be able to read your source strings too.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000141
142
143Unicode Type Object:
144--------------------
145
146Unicode objects should have the type UnicodeType with type name
147'unicode', made available through the standard types module.
148
149
150Unicode Output:
151---------------
152
153Unicode objects have a method .encode([encoding=<default encoding>])
154which returns a Python string encoding the Unicode string using the
155given scheme (see Codecs).
156
157 print u := print u.encode() # using the <default encoding>
158
159 str(u) := u.encode() # using the <default encoding>
160
161 repr(u) := "u%s" % repr(u.encode('unicode-escape'))
162
163Also see Internal Argument Parsing and Buffer Interface for details on
164how other APIs written in C will treat Unicode objects.
165
166
167Unicode Ordinals:
168-----------------
169
170Since Unicode 3.0 has a 32-bit ordinal character set, the implementation
171should provide 32-bit aware ordinal conversion APIs:
172
173 ord(u[:1]) (this is the standard ord() extended to work with Unicode
174 objects)
175 --> Unicode ordinal number (32-bit)
176
177 unichr(i)
178 --> Unicode object for character i (provided it is 32-bit);
179 ValueError otherwise
180
181Both APIs should go into __builtins__ just like their string
182counterparts ord() and chr().
183
184Note that Unicode provides space for private encodings. Usage of these
185can cause different output representations on different machines. This
186problem is not a Python or Unicode problem, but a machine setup and
187maintenance one.
188
189
190Comparison & Hash Value:
191------------------------
192
193Unicode objects should compare equal to other objects after these
194other objects have been coerced to Unicode. For strings this means
195that they are interpreted as Unicode string using the <default
196encoding>.
197
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000198Unicode objects should return the same hash value as their ASCII
199equivalent strings. Unicode strings holding non-ASCII values are not
200guaranteed to return the same hash values as the default encoded
201equivalent string representation.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000202
Fred Drake10dfd4c2000-04-13 14:12:38 +0000203When compared using cmp() (or PyObject_Compare()) the implementation
204should mask TypeErrors raised during the conversion to remain in synch
205with the string behavior. All other errors such as ValueErrors raised
206during coercion of strings to Unicode should not be masked and passed
207through to the user.
208
209In containment tests ('a' in u'abc' and u'a' in 'abc') both sides
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000210should be coerced to Unicode before applying the test. Errors occurring
Fred Drake10dfd4c2000-04-13 14:12:38 +0000211during coercion (e.g. None in u'abc') should not be masked.
212
213
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000214Coercion:
215---------
216
217Using Python strings and Unicode objects to form new objects should
218always coerce to the more precise format, i.e. Unicode objects.
219
220 u + s := u + unicode(s)
221
222 s + u := unicode(s) + u
223
224All string methods should delegate the call to an equivalent Unicode
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000225object method call by converting all involved strings to Unicode and
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000226then applying the arguments to the Unicode method of the same name,
227e.g.
228
229 string.join((s,u),sep) := (s + sep) + u
230
231 sep.join((s,u)) := (s + sep) + u
232
233For a discussion of %-formatting w/r to Unicode objects, see
234Formatting Markers.
235
236
237Exceptions:
238-----------
239
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000240UnicodeError is defined in the exceptions module as a subclass of
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000241ValueError. It is available at the C level via PyExc_UnicodeError.
242All exceptions related to Unicode encoding/decoding should be
243subclasses of UnicodeError.
244
245
246Codecs (Coder/Decoders) Lookup:
247-------------------------------
248
249A Codec (see Codec Interface Definition) search registry should be
250implemented by a module "codecs":
251
252 codecs.register(search_function)
253
254Search functions are expected to take one argument, the encoding name
Guido van Rossum25817642000-04-10 19:45:09 +0000255in all lower case letters and with hyphens and spaces converted to
256underscores, and return a tuple of functions (encoder, decoder,
257stream_reader, stream_writer) taking the following arguments:
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000258
259 encoder and decoder:
260 These must be functions or methods which have the same
261 interface as the .encode/.decode methods of Codec instances
262 (see Codec Interface). The functions/methods are expected to
263 work in a stateless mode.
264
265 stream_reader and stream_writer:
266 These need to be factory functions with the following
267 interface:
268
269 factory(stream,errors='strict')
270
271 The factory functions must return objects providing
272 the interfaces defined by StreamWriter/StreamReader resp.
273 (see Codec Interface). Stream codecs can maintain state.
274
275 Possible values for errors are defined in the Codec
276 section below.
277
278In case a search function cannot find a given encoding, it should
279return None.
280
281Aliasing support for encodings is left to the search functions
282to implement.
283
284The codecs module will maintain an encoding cache for performance
285reasons. Encodings are first looked up in the cache. If not found, the
286list of registered search functions is scanned. If no codecs tuple is
287found, a LookupError is raised. Otherwise, the codecs tuple is stored
288in the cache and returned to the caller.
289
290To query the Codec instance the following API should be used:
291
292 codecs.lookup(encoding)
293
294This will either return the found codecs tuple or raise a LookupError.
295
296
297Standard Codecs:
298----------------
299
300Standard codecs should live inside an encodings/ package directory in the
301Standard Python Code Library. The __init__.py file of that directory should
302include a Codec Lookup compatible search function implementing a lazy module
303based codec lookup.
304
305Python should provide a few standard codecs for the most relevant
306encodings, e.g.
307
308 'utf-8': 8-bit variable length encoding
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000309 'utf-16': 16-bit variable length encoding (little/big endian)
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000310 'utf-16-le': utf-16 but explicitly little endian
311 'utf-16-be': utf-16 but explicitly big endian
312 'ascii': 7-bit ASCII codepage
313 'iso-8859-1': ISO 8859-1 (Latin 1) codepage
314 'unicode-escape': See Unicode Constructors for a definition
315 'raw-unicode-escape': See Unicode Constructors for a definition
316 'native': Dump of the Internal Format used by Python
317
318Common aliases should also be provided per default, e.g. 'latin-1'
319for 'iso-8859-1'.
320
321Note: 'utf-16' should be implemented by using and requiring byte order
322marks (BOM) for file input/output.
323
324All other encodings such as the CJK ones to support Asian scripts
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000325should be implemented in separate packages which do not get included
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000326in the core Python distribution and are not a part of this proposal.
327
328
329Codecs Interface Definition:
330----------------------------
331
332The following base class should be defined in the module
333"codecs". They provide not only templates for use by encoding module
334implementors, but also define the interface which is expected by the
335Unicode implementation.
336
337Note that the Codec Interface defined here is well suitable for a
338larger range of applications. The Unicode implementation expects
339Unicode objects on input for .encode() and .write() and character
340buffer compatible objects on input for .decode(). Output of .encode()
341and .read() should be a Python string and .decode() must return an
342Unicode object.
343
344First, we have the stateless encoders/decoders. These do not work in
345chunks as the stream codecs (see below) do, because all components are
346expected to be available in memory.
347
348class Codec:
349
350 """ Defines the interface for stateless encoders/decoders.
351
352 The .encode()/.decode() methods may implement different error
353 handling schemes by providing the errors argument. These
354 string values are defined:
355
356 'strict' - raise an error (or a subclass)
357 'ignore' - ignore the character and continue with the next
358 'replace' - replace with a suitable replacement character;
359 Python will use the official U+FFFD REPLACEMENT
360 CHARACTER for the builtin Unicode codecs.
361
362 """
363 def encode(self,input,errors='strict'):
364
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000365 """ Encodes the object input and returns a tuple (output
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000366 object, length consumed).
367
368 errors defines the error handling to apply. It defaults to
369 'strict' handling.
370
371 The method may not store state in the Codec instance. Use
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000372 StreamCodec for codecs which have to keep state in order to
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000373 make encoding/decoding efficient.
374
375 """
376 ...
377
378 def decode(self,input,errors='strict'):
379
380 """ Decodes the object input and returns a tuple (output
381 object, length consumed).
382
383 input must be an object which provides the bf_getreadbuf
384 buffer slot. Python strings, buffer objects and memory
385 mapped files are examples of objects providing this slot.
386
387 errors defines the error handling to apply. It defaults to
388 'strict' handling.
389
390 The method may not store state in the Codec instance. Use
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000391 StreamCodec for codecs which have to keep state in order to
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000392 make encoding/decoding efficient.
393
394 """
395 ...
396
397StreamWriter and StreamReader define the interface for stateful
398encoders/decoders which work on streams. These allow processing of the
399data in chunks to efficiently use memory. If you have large strings in
400memory, you may want to wrap them with cStringIO objects and then use
401these codecs on them to be able to do chunk processing as well,
402e.g. to provide progress information to the user.
403
404class StreamWriter(Codec):
405
406 def __init__(self,stream,errors='strict'):
407
408 """ Creates a StreamWriter instance.
409
410 stream must be a file-like object open for writing
411 (binary) data.
412
413 The StreamWriter may implement different error handling
414 schemes by providing the errors keyword argument. These
415 parameters are defined:
416
417 'strict' - raise a ValueError (or a subclass)
418 'ignore' - ignore the character and continue with the next
419 'replace'- replace with a suitable replacement character
420
421 """
422 self.stream = stream
423 self.errors = errors
424
425 def write(self,object):
426
427 """ Writes the object's contents encoded to self.stream.
428 """
429 data, consumed = self.encode(object,self.errors)
430 self.stream.write(data)
431
Fred Drake10dfd4c2000-04-13 14:12:38 +0000432 def writelines(self, list):
433
434 """ Writes the concatenated list of strings to the stream
435 using .write().
436 """
437 self.write(''.join(list))
438
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000439 def reset(self):
440
441 """ Flushes and resets the codec buffers used for keeping state.
442
443 Calling this method should ensure that the data on the
444 output is put into a clean state, that allows appending
445 of new fresh data without having to rescan the whole
446 stream to recover state.
447
448 """
449 pass
450
451 def __getattr__(self,name,
452
453 getattr=getattr):
454
455 """ Inherit all other methods from the underlying stream.
456 """
457 return getattr(self.stream,name)
458
459class StreamReader(Codec):
460
461 def __init__(self,stream,errors='strict'):
462
463 """ Creates a StreamReader instance.
464
465 stream must be a file-like object open for reading
466 (binary) data.
467
468 The StreamReader may implement different error handling
469 schemes by providing the errors keyword argument. These
470 parameters are defined:
471
472 'strict' - raise a ValueError (or a subclass)
473 'ignore' - ignore the character and continue with the next
474 'replace'- replace with a suitable replacement character;
475
476 """
477 self.stream = stream
478 self.errors = errors
479
480 def read(self,size=-1):
481
482 """ Decodes data from the stream self.stream and returns the
483 resulting object.
484
485 size indicates the approximate maximum number of bytes to
486 read from the stream for decoding purposes. The decoder
487 can modify this setting as appropriate. The default value
488 -1 indicates to read and decode as much as possible. size
489 is intended to prevent having to decode huge files in one
490 step.
491
492 The method should use a greedy read strategy meaning that
493 it should read as much data as is allowed within the
494 definition of the encoding and the given size, e.g. if
495 optional encoding endings or state markers are available
496 on the stream, these should be read too.
497
498 """
499 # Unsliced reading:
500 if size < 0:
501 return self.decode(self.stream.read())[0]
502
503 # Sliced reading:
504 read = self.stream.read
505 decode = self.decode
506 data = read(size)
507 i = 0
508 while 1:
509 try:
510 object, decodedbytes = decode(data)
511 except ValueError,why:
512 # This method is slow but should work under pretty much
513 # all conditions; at most 10 tries are made
514 i = i + 1
515 newdata = read(1)
516 if not newdata or i > 10:
517 raise
518 data = data + newdata
519 else:
520 return object
521
Fred Drake10dfd4c2000-04-13 14:12:38 +0000522 def readline(self, size=None):
523
524 """ Read one line from the input stream and return the
525 decoded data.
526
527 Note: Unlike the .readlines() method, this method inherits
528 the line breaking knowledge from the underlying stream's
529 .readline() method -- there is currently no support for
530 line breaking using the codec decoder due to lack of line
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000531 buffering. Subclasses should however, if possible, try to
Fred Drake10dfd4c2000-04-13 14:12:38 +0000532 implement this method using their own knowledge of line
533 breaking.
534
535 size, if given, is passed as size argument to the stream's
536 .readline() method.
537
538 """
539 if size is None:
540 line = self.stream.readline()
541 else:
542 line = self.stream.readline(size)
543 return self.decode(line)[0]
544
545 def readlines(self, sizehint=0):
546
547 """ Read all lines available on the input stream
548 and return them as list of lines.
549
550 Line breaks are implemented using the codec's decoder
551 method and are included in the list entries.
552
553 sizehint, if given, is passed as size argument to the
554 stream's .read() method.
555
556 """
557 if sizehint is None:
558 data = self.stream.read()
559 else:
560 data = self.stream.read(sizehint)
561 return self.decode(data)[0].splitlines(1)
562
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000563 def reset(self):
564
565 """ Resets the codec buffers used for keeping state.
566
567 Note that no stream repositioning should take place.
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000568 This method is primarily intended to be able to recover
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000569 from decoding errors.
570
571 """
572 pass
573
574 def __getattr__(self,name,
575
576 getattr=getattr):
577
578 """ Inherit all other methods from the underlying stream.
579 """
580 return getattr(self.stream,name)
581
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000582
583Stream codec implementors are free to combine the StreamWriter and
584StreamReader interfaces into one class. Even combining all these with
585the Codec class should be possible.
586
587Implementors are free to add additional methods to enhance the codec
588functionality or provide extra state information needed for them to
589work. The internal codec implementation will only use the above
590interfaces, though.
591
592It is not required by the Unicode implementation to use these base
593classes, only the interfaces must match; this allows writing Codecs as
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000594extension types.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000595
596As guideline, large mapping tables should be implemented using static
597C data in separate (shared) extension modules. That way multiple
598processes can share the same data.
599
600A tool to auto-convert Unicode mapping files to mapping modules should be
601provided to simplify support for additional mappings (see References).
602
603
604Whitespace:
605-----------
606
607The .split() method will have to know about what is considered
608whitespace in Unicode.
609
610
611Case Conversion:
612----------------
613
614Case conversion is rather complicated with Unicode data, since there
615are many different conditions to respect. See
616
617 http://www.unicode.org/unicode/reports/tr13/
618
619for some guidelines on implementing case conversion.
620
621For Python, we should only implement the 1-1 conversions included in
622Unicode. Locale dependent and other special case conversions (see the
623Unicode standard file SpecialCasing.txt) should be left to user land
624routines and not go into the core interpreter.
625
626The methods .capitalize() and .iscapitalized() should follow the case
627mapping algorithm defined in the above technical report as closely as
628possible.
629
630
631Line Breaks:
632------------
633
634Line breaking should be done for all Unicode characters having the B
635property as well as the combinations CRLF, CR, LF (interpreted in that
636order) and other special line separators defined by the standard.
637
638The Unicode type should provide a .splitlines() method which returns a
639list of lines according to the above specification. See Unicode
640Methods.
641
642
643Unicode Character Properties:
644-----------------------------
645
646A separate module "unicodedata" should provide a compact interface to
647all Unicode character properties defined in the standard's
648UnicodeData.txt file.
649
650Among other things, these properties provide ways to recognize
651numbers, digits, spaces, whitespace, etc.
652
653Since this module will have to provide access to all Unicode
654characters, it will eventually have to contain the data from
655UnicodeData.txt which takes up around 600kB. For this reason, the data
656should be stored in static C data. This enables compilation as shared
657module which the underlying OS can shared between processes (unlike
658normal Python code modules).
659
660There should be a standard Python interface for accessing this information
661so that other implementors can plug in their own possibly enhanced versions,
662e.g. ones that do decompressing of the data on-the-fly.
663
664
665Private Code Point Areas:
666-------------------------
667
668Support for these is left to user land Codecs and not explicitly
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000669integrated into the core. Note that due to the Internal Format being
670implemented, only the area between \uE000 and \uF8FF is usable for
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000671private encodings.
672
673
674Internal Format:
675----------------
676
677The internal format for Unicode objects should use a Python specific
678fixed format <PythonUnicode> implemented as 'unsigned short' (or
679another unsigned numeric type having 16 bits). Byte order is platform
680dependent.
681
682This format will hold UTF-16 encodings of the corresponding Unicode
683ordinals. The Python Unicode implementation will address these values
684as if they were UCS-2 values. UCS-2 and UTF-16 are the same for all
685currently defined Unicode character points. UTF-16 without surrogates
686provides access to about 64k characters and covers all characters in
687the Basic Multilingual Plane (BMP) of Unicode.
688
689It is the Codec's responsibility to ensure that the data they pass to
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000690the Unicode object constructor respects this assumption. The
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000691constructor does not check the data for Unicode compliance or use of
692surrogates.
693
694Future implementations can extend the 32 bit restriction to the full
695set of all UTF-16 addressable characters (around 1M characters).
696
Marc-André Lemburgbfa36f52000-06-08 17:51:33 +0000697The Unicode API should provide interface routines from <PythonUnicode>
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000698to the compiler's wchar_t which can be 16 or 32 bit depending on the
699compiler/libc/platform being used.
700
701Unicode objects should have a pointer to a cached Python string object
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000702<defenc> holding the object's value using the <default encoding>.
703This is needed for performance and internal parsing (see Internal
704Argument Parsing) reasons. The buffer is filled when the first
705conversion request to the <default encoding> is issued on the object.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000706
707Interning is not needed (for now), since Python identifiers are
708defined as being ASCII only.
709
710codecs.BOM should return the byte order mark (BOM) for the format
711used internally. The codecs module should provide the following
712additional constants for convenience and reference (codecs.BOM will
713either be BOM_BE or BOM_LE depending on the platform):
714
715 BOM_BE: '\376\377'
716 (corresponds to Unicode U+0000FEFF in UTF-16 on big endian
717 platforms == ZERO WIDTH NO-BREAK SPACE)
718
719 BOM_LE: '\377\376'
720 (corresponds to Unicode U+0000FFFE in UTF-16 on little endian
721 platforms == defined as being an illegal Unicode character)
722
723 BOM4_BE: '\000\000\376\377'
724 (corresponds to Unicode U+0000FEFF in UCS-4)
725
726 BOM4_LE: '\377\376\000\000'
727 (corresponds to Unicode U+0000FFFE in UCS-4)
728
729Note that Unicode sees big endian byte order as being "correct". The
730swapped order is taken to be an indicator for a "wrong" format, hence
731the illegal character definition.
732
733The configure script should provide aid in deciding whether Python can
734use the native wchar_t type or not (it has to be a 16-bit unsigned
735type).
736
737
738Buffer Interface:
739-----------------
740
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +0000741Implement the buffer interface using the <defenc> Python string object
742as basis for bf_getcharbuf and the internal buffer for
743bf_getreadbuf. If bf_getcharbuf is requested and the <defenc> object
744does not yet exist, it is created first.
745
746Note that as special case, the parser marker "s#" will not return raw
747Unicode UTF-16 data (which the bf_getreadbuf returns), but instead
748tries to encode the Unicode object using the default encoding and then
749returns a pointer to the resulting string object (or raises an
750exception in case the conversion fails). This was done in order to
751prevent accidentely writing binary data to an output stream which the
752other end might not recognize.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000753
754This has the advantage of being able to write to output streams (which
755typically use this interface) without additional specification of the
756encoding to use.
757
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +0000758If you need to access the read buffer interface of Unicode objects,
759use the PyObject_AsReadBuffer() interface.
760
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000761The internal format can also be accessed using the 'unicode-internal'
762codec, e.g. via u.encode('unicode-internal').
763
764
765Pickle/Marshalling:
766-------------------
767
768Should have native Unicode object support. The objects should be
769encoded using platform independent encodings.
770
771Marshal should use UTF-8 and Pickle should either choose
772Raw-Unicode-Escape (in text mode) or UTF-8 (in binary mode) as
773encoding. Using UTF-8 instead of UTF-16 has the advantage of
774eliminating the need to store a BOM mark.
775
776
777Regular Expressions:
778--------------------
779
780Secret Labs AB is working on a Unicode-aware regular expression
781machinery. It works on plain 8-bit, UCS-2, and (optionally) UCS-4
782internal character buffers.
783
784Also see
785
786 http://www.unicode.org/unicode/reports/tr18/
787
788for some remarks on how to treat Unicode REs.
789
790
791Formatting Markers:
792-------------------
793
794Format markers are used in Python format strings. If Python strings
795are used as format strings, the following interpretations should be in
796effect:
797
Fred Drake10dfd4c2000-04-13 14:12:38 +0000798 '%s': For Unicode objects this will cause coercion of the
799 whole format string to Unicode. Note that
800 you should use a Unicode format string to start
801 with for performance reasons.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000802
803In case the format string is an Unicode object, all parameters are coerced
804to Unicode first and then put together and formatted according to the format
805string. Numbers are first converted to strings and then to Unicode.
806
807 '%s': Python strings are interpreted as Unicode
808 string using the <default encoding>. Unicode
809 objects are taken as is.
810
811All other string formatters should work accordingly.
812
813Example:
814
815u"%s %s" % (u"abc", "abc") == u"abc abc"
816
817
818Internal Argument Parsing:
819--------------------------
820
821These markers are used by the PyArg_ParseTuple() APIs:
822
Guido van Rossumd8855fd2000-03-24 22:14:19 +0000823 "U": Check for Unicode object and return a pointer to it
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000824
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000825 "s": For Unicode objects: return a pointer to the object's
826 <defenc> buffer (which uses the <default encoding>).
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000827
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +0000828 "s#": Access to the default encoded version of the Unicode object
829 (see Buffer Interface); note that the length relates to the length
830 of the default encoded string rather than the Unicode object length.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000831
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +0000832 "t#": Same as "s#".
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000833
Guido van Rossumd8855fd2000-03-24 22:14:19 +0000834 "es":
835 Takes two parameters: encoding (const char *) and
836 buffer (char **).
837
838 The input object is first coerced to Unicode in the usual way
839 and then encoded into a string using the given encoding.
840
841 On output, a buffer of the needed size is allocated and
842 returned through *buffer as NULL-terminated string.
843 The encoded may not contain embedded NULL characters.
Guido van Rossum24bdb042000-03-28 20:29:59 +0000844 The caller is responsible for calling PyMem_Free()
845 to free the allocated *buffer after usage.
Guido van Rossumd8855fd2000-03-24 22:14:19 +0000846
847 "es#":
848 Takes three parameters: encoding (const char *),
849 buffer (char **) and buffer_len (int *).
850
851 The input object is first coerced to Unicode in the usual way
852 and then encoded into a string using the given encoding.
853
854 If *buffer is non-NULL, *buffer_len must be set to sizeof(buffer)
855 on input. Output is then copied to *buffer.
856
857 If *buffer is NULL, a buffer of the needed size is
858 allocated and output copied into it. *buffer is then
Guido van Rossum24bdb042000-03-28 20:29:59 +0000859 updated to point to the allocated memory area.
860 The caller is responsible for calling PyMem_Free()
861 to free the allocated *buffer after usage.
Guido van Rossumd8855fd2000-03-24 22:14:19 +0000862
863 In both cases *buffer_len is updated to the number of
864 characters written (excluding the trailing NULL-byte).
865 The output buffer is assured to be NULL-terminated.
866
867Examples:
868
869Using "es#" with auto-allocation:
870
871 static PyObject *
872 test_parser(PyObject *self,
873 PyObject *args)
874 {
875 PyObject *str;
876 const char *encoding = "latin-1";
877 char *buffer = NULL;
878 int buffer_len = 0;
879
880 if (!PyArg_ParseTuple(args, "es#:test_parser",
881 encoding, &buffer, &buffer_len))
882 return NULL;
883 if (!buffer) {
884 PyErr_SetString(PyExc_SystemError,
885 "buffer is NULL");
886 return NULL;
887 }
888 str = PyString_FromStringAndSize(buffer, buffer_len);
Guido van Rossum24bdb042000-03-28 20:29:59 +0000889 PyMem_Free(buffer);
Guido van Rossumd8855fd2000-03-24 22:14:19 +0000890 return str;
891 }
892
893Using "es" with auto-allocation returning a NULL-terminated string:
894
895 static PyObject *
896 test_parser(PyObject *self,
897 PyObject *args)
898 {
899 PyObject *str;
900 const char *encoding = "latin-1";
901 char *buffer = NULL;
902
903 if (!PyArg_ParseTuple(args, "es:test_parser",
904 encoding, &buffer))
905 return NULL;
906 if (!buffer) {
907 PyErr_SetString(PyExc_SystemError,
908 "buffer is NULL");
909 return NULL;
910 }
911 str = PyString_FromString(buffer);
Guido van Rossum24bdb042000-03-28 20:29:59 +0000912 PyMem_Free(buffer);
Guido van Rossumd8855fd2000-03-24 22:14:19 +0000913 return str;
914 }
915
916Using "es#" with a pre-allocated buffer:
917
918 static PyObject *
919 test_parser(PyObject *self,
920 PyObject *args)
921 {
922 PyObject *str;
923 const char *encoding = "latin-1";
924 char _buffer[10];
925 char *buffer = _buffer;
926 int buffer_len = sizeof(_buffer);
927
928 if (!PyArg_ParseTuple(args, "es#:test_parser",
929 encoding, &buffer, &buffer_len))
930 return NULL;
931 if (!buffer) {
932 PyErr_SetString(PyExc_SystemError,
933 "buffer is NULL");
934 return NULL;
935 }
936 str = PyString_FromStringAndSize(buffer, buffer_len);
937 return str;
938 }
939
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000940
941File/Stream Output:
942-------------------
943
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +0000944Since file.write(object) and most other stream writers use the "s#" or
945"t#" argument parsing marker for querying the data to write, the
946default encoded string version of the Unicode object will be written
947to the streams (see Buffer Interface).
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000948
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +0000949For explicit handling of files using Unicode, the standard stream
950codecs as available through the codecs module should be used.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000951
Barry Warsaw51ac5802000-03-20 16:36:48 +0000952The codecs module should provide a short-cut open(filename,mode,encoding)
953available which also assures that mode contains the 'b' character when
954needed.
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +0000955
956
957File/Stream Input:
958------------------
959
960Only the user knows what encoding the input data uses, so no special
961magic is applied. The user will have to explicitly convert the string
962data to Unicode objects as needed or use the file wrappers defined in
963the codecs module (see File/Stream Output).
964
965
966Unicode Methods & Attributes:
967-----------------------------
968
969All Python string methods, plus:
970
971 .encode([encoding=<default encoding>][,errors="strict"])
972 --> see Unicode Output
973
974 .splitlines([include_breaks=0])
975 --> breaks the Unicode string into a list of (Unicode) lines;
976 returns the lines with line breaks included, if include_breaks
977 is true. See Line Breaks for a specification of how line breaking
978 is done.
979
980
981Code Base:
982----------
983
984We should use Fredrik Lundh's Unicode object implementation as basis.
985It already implements most of the string methods needed and provides a
986well written code base which we can build upon.
987
988The object sharing implemented in Fredrik's implementation should
989be dropped.
990
991
992Test Cases:
993-----------
994
995Test cases should follow those in Lib/test/test_string.py and include
996additional checks for the Codec Registry and the Standard Codecs.
997
998
999References:
1000-----------
1001
1002Unicode Consortium:
1003 http://www.unicode.org/
1004
1005Unicode FAQ:
1006 http://www.unicode.org/unicode/faq/
1007
1008Unicode 3.0:
1009 http://www.unicode.org/unicode/standard/versions/Unicode3.0.html
1010
1011Unicode-TechReports:
1012 http://www.unicode.org/unicode/reports/techreports.html
1013
1014Unicode-Mappings:
1015 ftp://ftp.unicode.org/Public/MAPPINGS/
1016
1017Introduction to Unicode (a little outdated by still nice to read):
1018 http://www.nada.kth.se/i18n/ucs/unicode-iso10646-oview.html
1019
Barry Warsaw51ac5802000-03-20 16:36:48 +00001020For comparison:
Fred Drakea69ef822000-05-09 19:58:19 +00001021 Introducing Unicode to ECMAScript (aka JavaScript) --
Barry Warsaw51ac5802000-03-20 16:36:48 +00001022 http://www-4.ibm.com/software/developer/library/internationalization-support.html
1023
Fred Drake10dfd4c2000-04-13 14:12:38 +00001024IANA Character Set Names:
1025 ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets
1026
Fred Drakea69ef822000-05-09 19:58:19 +00001027Discussion of UTF-8 and Unicode support for POSIX and Linux:
1028 http://www.cl.cam.ac.uk/~mgk25/unicode.html
1029
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +00001030Encodings:
1031
1032 Overview:
1033 http://czyborra.com/utf/
1034
1035 UTC-2:
1036 http://www.uazone.com/multiling/unicode/ucs2.html
1037
1038 UTF-7:
1039 Defined in RFC2152, e.g.
1040 http://www.uazone.com/multiling/ml-docs/rfc2152.txt
1041
1042 UTF-8:
1043 Defined in RFC2279, e.g.
1044 http://info.internet.isi.edu/in-notes/rfc/files/rfc2279.txt
1045
1046 UTF-16:
1047 http://www.uazone.com/multiling/unicode/wg2n1035.html
1048
1049
1050History of this Proposal:
1051-------------------------
Marc-André Lemburg5cd2f0d2000-09-21 21:21:59 +000010521.7: Added note about the changed behaviour of "s#".
Marc-André Lemburgbff879c2000-08-03 18:46:08 +000010531.6: Changed <defencstr> to <defenc> since this is the name used in the
1054 implementation. Added notes about the usage of <defenc> in the
1055 buffer protocol implementation.
10561.5: Added notes about setting the <default encoding>. Fixed some
1057 typos (thanks to Andrew Kuchling). Changed <defencstr> to <utf8str>.
Fred Drake10dfd4c2000-04-13 14:12:38 +000010581.4: Added note about mixed type comparisons and contains tests.
1059 Changed treating of Unicode objects in format strings (if used
1060 with '%s' % u they will now cause the format string to be
1061 coerced to Unicode, thus producing a Unicode object on return).
1062 Added link to IANA charset names (thanks to Lars Marius Garshol).
1063 Added new codec methods .readline(), .readlines() and .writelines().
Guido van Rossumd8855fd2000-03-24 22:14:19 +000010641.3: Added new "es" and "es#" parser markers
Barry Warsaw51ac5802000-03-20 16:36:48 +000010651.2: Removed POD about codecs.open()
Guido van Rossum9ed0d1e2000-03-10 23:14:11 +000010661.1: Added note about comparisons and hash values. Added note about
1067 case mapping algorithms. Changed stream codecs .read() and
1068 .write() method to match the standard file-like object methods
1069 (bytes consumed information is no longer returned by the methods)
10701.0: changed encode Codec method to be symmetric to the decode method
1071 (they both return (object, data consumed) now and thus become
1072 interchangeable); removed __init__ method of Codec class (the
1073 methods are stateless) and moved the errors argument down to the
1074 methods; made the Codec design more generic w/r to type of input
1075 and output objects; changed StreamWriter.flush to StreamWriter.reset
1076 in order to avoid overriding the stream's .flush() method;
1077 renamed .breaklines() to .splitlines(); renamed the module unicodec
1078 to codecs; modified the File I/O section to refer to the stream codecs.
10790.9: changed errors keyword argument definition; added 'replace' error
1080 handling; changed the codec APIs to accept buffer like objects on
1081 input; some minor typo fixes; added Whitespace section and
1082 included references for Unicode characters that have the whitespace
1083 and the line break characteristic; added note that search functions
1084 can expect lower-case encoding names; dropped slicing and offsets
1085 in the codec APIs
10860.8: added encodings package and raw unicode escape encoding; untabified
1087 the proposal; added notes on Unicode format strings; added
1088 .breaklines() method
10890.7: added a whole new set of codec APIs; added a different encoder
1090 lookup scheme; fixed some names
10910.6: changed "s#" to "t#"; changed <defencbuf> to <defencstr> holding
1092 a real Python string object; changed Buffer Interface to delegate
1093 requests to <defencstr>'s buffer interface; removed the explicit
1094 reference to the unicodec.codecs dictionary (the module can implement
1095 this in way fit for the purpose); removed the settable default
1096 encoding; move UnicodeError from unicodec to exceptions; "s#"
1097 not returns the internal data; passed the UCS-2/UTF-16 checking
1098 from the Unicode constructor to the Codecs
10990.5: moved sys.bom to unicodec.BOM; added sections on case mapping,
1100 private use encodings and Unicode character properties
11010.4: added Codec interface, notes on %-formatting, changed some encoding
1102 details, added comments on stream wrappers, fixed some discussion
1103 points (most important: Internal Format), clarified the
1104 'unicode-escape' encoding, added encoding references
11050.3: added references, comments on codec modules, the internal format,
1106 bf_getcharbuffer and the RE engine; added 'unicode-escape' encoding
1107 proposed by Tim Peters and fixed repr(u) accordingly
11080.2: integrated Guido's suggestions, added stream codecs and file
1109 wrapping
11100.1: first version
1111
1112
1113-----------------------------------------------------------------------------
1114Written by Marc-Andre Lemburg, 1999-2000, mal@lemburg.com
1115-----------------------------------------------------------------------------