code
stringlengths
1
1.72M
language
stringclasses
1 value
""" Python 'ascii' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = staticmethod(codecs.ascii_encode) decode = staticmethod(codecs.ascii_decode) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass class StreamConverter(StreamWriter,StreamReader): encode = codecs.ascii_decode decode = codecs.ascii_encode ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1254.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: 0x0153, # LATIN SMALL LIGATURE OE 0x009d: None, # UNDEFINED 0x009e: None, # UNDEFINED 0x009f: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00d0: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00dd: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x00de: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00f0: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00fd: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00fe: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# This module implements the RFCs 3490 (IDNA) and 3491 (Nameprep) import stringprep, unicodedata, re, codecs # IDNA section 3.1 dots = re.compile(u"[\u002E\u3002\uFF0E\uFF61]") # IDNA section 5 ace_prefix = "xn--" uace_prefix = unicode(ace_prefix, "ascii") # This assumes query strings, so AllowUnassigned is true def nameprep(label): # Map newlabel = [] for c in label: if stringprep.in_table_b1(c): # Map to nothing continue newlabel.append(stringprep.map_table_b2(c)) label = u"".join(newlabel) # Normalize label = unicodedata.normalize("NFKC", label) # Prohibit for c in label: if stringprep.in_table_c12(c) or \ stringprep.in_table_c22(c) or \ stringprep.in_table_c3(c) or \ stringprep.in_table_c4(c) or \ stringprep.in_table_c5(c) or \ stringprep.in_table_c6(c) or \ stringprep.in_table_c7(c) or \ stringprep.in_table_c8(c) or \ stringprep.in_table_c9(c): raise UnicodeError, "Invalid character %s" % repr(c) # Check bidi RandAL = map(stringprep.in_table_d1, label) for c in RandAL: if c: # There is a RandAL char in the string. Must perform further # tests: # 1) The characters in section 5.8 MUST be prohibited. # This is table C.8, which was already checked # 2) If a string contains any RandALCat character, the string # MUST NOT contain any LCat character. if filter(stringprep.in_table_d2, label): raise UnicodeError, "Violation of BIDI requirement 2" # 3) If a string contains any RandALCat character, a # RandALCat character MUST be the first character of the # string, and a RandALCat character MUST be the last # character of the string. if not RandAL[0] or not RandAL[-1]: raise UnicodeError, "Violation of BIDI requirement 3" return label def ToASCII(label): try: # Step 1: try ASCII label = label.encode("ascii") except UnicodeError: pass else: # Skip to step 3: UseSTD3ASCIIRules is false, so # Skip to step 8. if 0 < len(label) < 64: return label raise UnicodeError, "label too long" # Step 2: nameprep label = nameprep(label) # Step 3: UseSTD3ASCIIRules is false # Step 4: try ASCII try: label = label.encode("ascii") except UnicodeError: pass else: # Skip to step 8. if 0 < len(label) < 64: return label raise UnicodeError, "label too long" # Step 5: Check ACE prefix if label.startswith(uace_prefix): raise UnicodeError, "Label starts with ACE prefix" # Step 6: Encode with PUNYCODE label = label.encode("punycode") # Step 7: Prepend ACE prefix label = ace_prefix + label # Step 8: Check size if 0 < len(label) < 64: return label raise UnicodeError, "label too long" def ToUnicode(label): # Step 1: Check for ASCII if isinstance(label, str): pure_ascii = True else: try: label = label.encode("ascii") pure_ascii = True except UnicodeError: pure_ascii = False if not pure_ascii: # Step 2: Perform nameprep label = nameprep(label) # It doesn't say this, but apparently, it should be ASCII now try: label = label.encode("ascii") except UnicodeError: raise UnicodeError, "Invalid character in IDN label" # Step 3: Check for ACE prefix if not label.startswith(ace_prefix): return unicode(label, "ascii") # Step 4: Remove ACE prefix label1 = label[len(ace_prefix):] # Step 5: Decode using PUNYCODE result = label1.decode("punycode") # Step 6: Apply ToASCII label2 = ToASCII(result) # Step 7: Compare the result of step 6 with the one of step 3 # label2 will already be in lower case. if label.lower() != label2: raise UnicodeError, ("IDNA does not round-trip", label, label2) # Step 8: return the result of step 5 return result ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): if errors != 'strict': # IDNA is quite clear that implementations must be strict raise UnicodeError, "unsupported error handling "+errors result = [] labels = dots.split(input) if labels and len(labels[-1])==0: trailing_dot = '.' del labels[-1] else: trailing_dot = '' for label in labels: result.append(ToASCII(label)) # Join with U+002E return ".".join(result)+trailing_dot, len(input) def decode(self,input,errors='strict'): if errors != 'strict': raise UnicodeError, "Unsupported error handling "+errors # IDNA allows decoding to operate on Unicode strings, too. if isinstance(input, unicode): labels = dots.split(input) else: # Must be ASCII string input = str(input) unicode(input, "ascii") labels = input.split(".") if labels and len(labels[-1]) == 0: trailing_dot = u'.' del labels[-1] else: trailing_dot = u'' result = [] for label in labels: result.append(ToUnicode(label)) return u".".join(result)+trailing_dot, len(input) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-14.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x1e02, # LATIN CAPITAL LETTER B WITH DOT ABOVE 0x00a2: 0x1e03, # LATIN SMALL LETTER B WITH DOT ABOVE 0x00a4: 0x010a, # LATIN CAPITAL LETTER C WITH DOT ABOVE 0x00a5: 0x010b, # LATIN SMALL LETTER C WITH DOT ABOVE 0x00a6: 0x1e0a, # LATIN CAPITAL LETTER D WITH DOT ABOVE 0x00a8: 0x1e80, # LATIN CAPITAL LETTER W WITH GRAVE 0x00aa: 0x1e82, # LATIN CAPITAL LETTER W WITH ACUTE 0x00ab: 0x1e0b, # LATIN SMALL LETTER D WITH DOT ABOVE 0x00ac: 0x1ef2, # LATIN CAPITAL LETTER Y WITH GRAVE 0x00af: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00b0: 0x1e1e, # LATIN CAPITAL LETTER F WITH DOT ABOVE 0x00b1: 0x1e1f, # LATIN SMALL LETTER F WITH DOT ABOVE 0x00b2: 0x0120, # LATIN CAPITAL LETTER G WITH DOT ABOVE 0x00b3: 0x0121, # LATIN SMALL LETTER G WITH DOT ABOVE 0x00b4: 0x1e40, # LATIN CAPITAL LETTER M WITH DOT ABOVE 0x00b5: 0x1e41, # LATIN SMALL LETTER M WITH DOT ABOVE 0x00b7: 0x1e56, # LATIN CAPITAL LETTER P WITH DOT ABOVE 0x00b8: 0x1e81, # LATIN SMALL LETTER W WITH GRAVE 0x00b9: 0x1e57, # LATIN SMALL LETTER P WITH DOT ABOVE 0x00ba: 0x1e83, # LATIN SMALL LETTER W WITH ACUTE 0x00bb: 0x1e60, # LATIN CAPITAL LETTER S WITH DOT ABOVE 0x00bc: 0x1ef3, # LATIN SMALL LETTER Y WITH GRAVE 0x00bd: 0x1e84, # LATIN CAPITAL LETTER W WITH DIAERESIS 0x00be: 0x1e85, # LATIN SMALL LETTER W WITH DIAERESIS 0x00bf: 0x1e61, # LATIN SMALL LETTER S WITH DOT ABOVE 0x00d0: 0x0174, # LATIN CAPITAL LETTER W WITH CIRCUMFLEX 0x00d7: 0x1e6a, # LATIN CAPITAL LETTER T WITH DOT ABOVE 0x00de: 0x0176, # LATIN CAPITAL LETTER Y WITH CIRCUMFLEX 0x00f0: 0x0175, # LATIN SMALL LETTER W WITH CIRCUMFLEX 0x00f7: 0x1e6b, # LATIN SMALL LETTER T WITH DOT ABOVE 0x00fe: 0x0177, # LATIN SMALL LETTER Y WITH CIRCUMFLEX }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP864.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0025: 0x066a, # ARABIC PERCENT SIGN 0x0080: 0x00b0, # DEGREE SIGN 0x0081: 0x00b7, # MIDDLE DOT 0x0082: 0x2219, # BULLET OPERATOR 0x0083: 0x221a, # SQUARE ROOT 0x0084: 0x2592, # MEDIUM SHADE 0x0085: 0x2500, # FORMS LIGHT HORIZONTAL 0x0086: 0x2502, # FORMS LIGHT VERTICAL 0x0087: 0x253c, # FORMS LIGHT VERTICAL AND HORIZONTAL 0x0088: 0x2524, # FORMS LIGHT VERTICAL AND LEFT 0x0089: 0x252c, # FORMS LIGHT DOWN AND HORIZONTAL 0x008a: 0x251c, # FORMS LIGHT VERTICAL AND RIGHT 0x008b: 0x2534, # FORMS LIGHT UP AND HORIZONTAL 0x008c: 0x2510, # FORMS LIGHT DOWN AND LEFT 0x008d: 0x250c, # FORMS LIGHT DOWN AND RIGHT 0x008e: 0x2514, # FORMS LIGHT UP AND RIGHT 0x008f: 0x2518, # FORMS LIGHT UP AND LEFT 0x0090: 0x03b2, # GREEK SMALL BETA 0x0091: 0x221e, # INFINITY 0x0092: 0x03c6, # GREEK SMALL PHI 0x0093: 0x00b1, # PLUS-OR-MINUS SIGN 0x0094: 0x00bd, # FRACTION 1/2 0x0095: 0x00bc, # FRACTION 1/4 0x0096: 0x2248, # ALMOST EQUAL TO 0x0097: 0x00ab, # LEFT POINTING GUILLEMET 0x0098: 0x00bb, # RIGHT POINTING GUILLEMET 0x0099: 0xfef7, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM 0x009a: 0xfef8, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM 0x009b: None, # UNDEFINED 0x009c: None, # UNDEFINED 0x009d: 0xfefb, # ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM 0x009e: 0xfefc, # ARABIC LIGATURE LAM WITH ALEF FINAL FORM 0x009f: None, # UNDEFINED 0x00a1: 0x00ad, # SOFT HYPHEN 0x00a2: 0xfe82, # ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM 0x00a5: 0xfe84, # ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM 0x00a6: None, # UNDEFINED 0x00a7: None, # UNDEFINED 0x00a8: 0xfe8e, # ARABIC LETTER ALEF FINAL FORM 0x00a9: 0xfe8f, # ARABIC LETTER BEH ISOLATED FORM 0x00aa: 0xfe95, # ARABIC LETTER TEH ISOLATED FORM 0x00ab: 0xfe99, # ARABIC LETTER THEH ISOLATED FORM 0x00ac: 0x060c, # ARABIC COMMA 0x00ad: 0xfe9d, # ARABIC LETTER JEEM ISOLATED FORM 0x00ae: 0xfea1, # ARABIC LETTER HAH ISOLATED FORM 0x00af: 0xfea5, # ARABIC LETTER KHAH ISOLATED FORM 0x00b0: 0x0660, # ARABIC-INDIC DIGIT ZERO 0x00b1: 0x0661, # ARABIC-INDIC DIGIT ONE 0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO 0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE 0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR 0x00b5: 0x0665, # ARABIC-INDIC DIGIT FIVE 0x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX 0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN 0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT 0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE 0x00ba: 0xfed1, # ARABIC LETTER FEH ISOLATED FORM 0x00bb: 0x061b, # ARABIC SEMICOLON 0x00bc: 0xfeb1, # ARABIC LETTER SEEN ISOLATED FORM 0x00bd: 0xfeb5, # ARABIC LETTER SHEEN ISOLATED FORM 0x00be: 0xfeb9, # ARABIC LETTER SAD ISOLATED FORM 0x00bf: 0x061f, # ARABIC QUESTION MARK 0x00c0: 0x00a2, # CENT SIGN 0x00c1: 0xfe80, # ARABIC LETTER HAMZA ISOLATED FORM 0x00c2: 0xfe81, # ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM 0x00c3: 0xfe83, # ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM 0x00c4: 0xfe85, # ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM 0x00c5: 0xfeca, # ARABIC LETTER AIN FINAL FORM 0x00c6: 0xfe8b, # ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM 0x00c7: 0xfe8d, # ARABIC LETTER ALEF ISOLATED FORM 0x00c8: 0xfe91, # ARABIC LETTER BEH INITIAL FORM 0x00c9: 0xfe93, # ARABIC LETTER TEH MARBUTA ISOLATED FORM 0x00ca: 0xfe97, # ARABIC LETTER TEH INITIAL FORM 0x00cb: 0xfe9b, # ARABIC LETTER THEH INITIAL FORM 0x00cc: 0xfe9f, # ARABIC LETTER JEEM INITIAL FORM 0x00cd: 0xfea3, # ARABIC LETTER HAH INITIAL FORM 0x00ce: 0xfea7, # ARABIC LETTER KHAH INITIAL FORM 0x00cf: 0xfea9, # ARABIC LETTER DAL ISOLATED FORM 0x00d0: 0xfeab, # ARABIC LETTER THAL ISOLATED FORM 0x00d1: 0xfead, # ARABIC LETTER REH ISOLATED FORM 0x00d2: 0xfeaf, # ARABIC LETTER ZAIN ISOLATED FORM 0x00d3: 0xfeb3, # ARABIC LETTER SEEN INITIAL FORM 0x00d4: 0xfeb7, # ARABIC LETTER SHEEN INITIAL FORM 0x00d5: 0xfebb, # ARABIC LETTER SAD INITIAL FORM 0x00d6: 0xfebf, # ARABIC LETTER DAD INITIAL FORM 0x00d7: 0xfec1, # ARABIC LETTER TAH ISOLATED FORM 0x00d8: 0xfec5, # ARABIC LETTER ZAH ISOLATED FORM 0x00d9: 0xfecb, # ARABIC LETTER AIN INITIAL FORM 0x00da: 0xfecf, # ARABIC LETTER GHAIN INITIAL FORM 0x00db: 0x00a6, # BROKEN VERTICAL BAR 0x00dc: 0x00ac, # NOT SIGN 0x00dd: 0x00f7, # DIVISION SIGN 0x00de: 0x00d7, # MULTIPLICATION SIGN 0x00df: 0xfec9, # ARABIC LETTER AIN ISOLATED FORM 0x00e0: 0x0640, # ARABIC TATWEEL 0x00e1: 0xfed3, # ARABIC LETTER FEH INITIAL FORM 0x00e2: 0xfed7, # ARABIC LETTER QAF INITIAL FORM 0x00e3: 0xfedb, # ARABIC LETTER KAF INITIAL FORM 0x00e4: 0xfedf, # ARABIC LETTER LAM INITIAL FORM 0x00e5: 0xfee3, # ARABIC LETTER MEEM INITIAL FORM 0x00e6: 0xfee7, # ARABIC LETTER NOON INITIAL FORM 0x00e7: 0xfeeb, # ARABIC LETTER HEH INITIAL FORM 0x00e8: 0xfeed, # ARABIC LETTER WAW ISOLATED FORM 0x00e9: 0xfeef, # ARABIC LETTER ALEF MAKSURA ISOLATED FORM 0x00ea: 0xfef3, # ARABIC LETTER YEH INITIAL FORM 0x00eb: 0xfebd, # ARABIC LETTER DAD ISOLATED FORM 0x00ec: 0xfecc, # ARABIC LETTER AIN MEDIAL FORM 0x00ed: 0xfece, # ARABIC LETTER GHAIN FINAL FORM 0x00ee: 0xfecd, # ARABIC LETTER GHAIN ISOLATED FORM 0x00ef: 0xfee1, # ARABIC LETTER MEEM ISOLATED FORM 0x00f0: 0xfe7d, # ARABIC SHADDA MEDIAL FORM 0x00f1: 0x0651, # ARABIC SHADDAH 0x00f2: 0xfee5, # ARABIC LETTER NOON ISOLATED FORM 0x00f3: 0xfee9, # ARABIC LETTER HEH ISOLATED FORM 0x00f4: 0xfeec, # ARABIC LETTER HEH MEDIAL FORM 0x00f5: 0xfef0, # ARABIC LETTER ALEF MAKSURA FINAL FORM 0x00f6: 0xfef2, # ARABIC LETTER YEH FINAL FORM 0x00f7: 0xfed0, # ARABIC LETTER GHAIN MEDIAL FORM 0x00f8: 0xfed5, # ARABIC LETTER QAF ISOLATED FORM 0x00f9: 0xfef5, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM 0x00fa: 0xfef6, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM 0x00fb: 0xfedd, # ARABIC LETTER LAM ISOLATED FORM 0x00fc: 0xfed9, # ARABIC LETTER KAF ISOLATED FORM 0x00fd: 0xfef1, # ARABIC LETTER YEH ISOLATED FORM 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: None, # UNDEFINED }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP866.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0410, # CYRILLIC CAPITAL LETTER A 0x0081: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x0082: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x0083: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x0084: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x0085: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x0086: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x0087: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x0088: 0x0418, # CYRILLIC CAPITAL LETTER I 0x0089: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x008a: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x008b: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x008c: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x008d: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x008e: 0x041e, # CYRILLIC CAPITAL LETTER O 0x008f: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x0090: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x0091: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x0092: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x0093: 0x0423, # CYRILLIC CAPITAL LETTER U 0x0094: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x0095: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x0096: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x0097: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x0098: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x0099: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x009a: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x009b: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x009c: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x009d: 0x042d, # CYRILLIC CAPITAL LETTER E 0x009e: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x009f: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00a0: 0x0430, # CYRILLIC SMALL LETTER A 0x00a1: 0x0431, # CYRILLIC SMALL LETTER BE 0x00a2: 0x0432, # CYRILLIC SMALL LETTER VE 0x00a3: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00a4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00a5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00a6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00a7: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00a8: 0x0438, # CYRILLIC SMALL LETTER I 0x00a9: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00aa: 0x043a, # CYRILLIC SMALL LETTER KA 0x00ab: 0x043b, # CYRILLIC SMALL LETTER EL 0x00ac: 0x043c, # CYRILLIC SMALL LETTER EM 0x00ad: 0x043d, # CYRILLIC SMALL LETTER EN 0x00ae: 0x043e, # CYRILLIC SMALL LETTER O 0x00af: 0x043f, # CYRILLIC SMALL LETTER PE 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x0440, # CYRILLIC SMALL LETTER ER 0x00e1: 0x0441, # CYRILLIC SMALL LETTER ES 0x00e2: 0x0442, # CYRILLIC SMALL LETTER TE 0x00e3: 0x0443, # CYRILLIC SMALL LETTER U 0x00e4: 0x0444, # CYRILLIC SMALL LETTER EF 0x00e5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00e6: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00e7: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00e8: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00e9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00ea: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00eb: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00ec: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00ed: 0x044d, # CYRILLIC SMALL LETTER E 0x00ee: 0x044e, # CYRILLIC SMALL LETTER YU 0x00ef: 0x044f, # CYRILLIC SMALL LETTER YA 0x00f0: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00f1: 0x0451, # CYRILLIC SMALL LETTER IO 0x00f2: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x00f3: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE 0x00f4: 0x0407, # CYRILLIC CAPITAL LETTER YI 0x00f5: 0x0457, # CYRILLIC SMALL LETTER YI 0x00f6: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U 0x00f7: 0x045e, # CYRILLIC SMALL LETTER SHORT U 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x2116, # NUMERO SIGN 0x00fd: 0x00a4, # CURRENCY SIGN 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'utf-16' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs, sys ### Codec APIs encode = codecs.utf_16_encode def decode(input, errors='strict'): return codecs.utf_16_decode(input, errors, True) class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): self.bom_written = False codecs.StreamWriter.__init__(self, stream, errors) def encode(self, input, errors='strict'): self.bom_written = True result = codecs.utf_16_encode(input, errors) if sys.byteorder == 'little': self.encode = codecs.utf_16_le_encode else: self.encode = codecs.utf_16_be_encode return result class StreamReader(codecs.StreamReader): def reset(self): codecs.StreamReader.reset(self) try: del self.decode except AttributeError: pass def decode(self, input, errors='strict'): (object, consumed, byteorder) = \ codecs.utf_16_ex_decode(input, errors, 0, False) if byteorder == -1: self.decode = codecs.utf_16_le_decode elif byteorder == 1: self.decode = codecs.utf_16_be_decode elif consumed>=2: raise UnicodeError,"UTF-16 stream does not start with BOM" return (object, consumed) ### encodings module API def getregentry(): return (encode,decode,StreamReader,StreamWriter)
Python
""" Python 'uu_codec' Codec - UU content transfer encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (mal@lemburg.com). Some details were adapted from uu.py which was written by Lance Ellinghouse and modified by Jack Jansen and Fredrik Lundh. """ import codecs, binascii ### Codec APIs def uu_encode(input,errors='strict',filename='<data>',mode=0666): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' from cStringIO import StringIO from binascii import b2a_uu infile = StringIO(input) outfile = StringIO() read = infile.read write = outfile.write # Encode write('begin %o %s\n' % (mode & 0777, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return (outfile.getvalue(), len(input)) def uu_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. Note: filename and file mode information in the input data is ignored. """ assert errors == 'strict' from cStringIO import StringIO from binascii import a2b_uu infile = StringIO(input) outfile = StringIO() readline = infile.readline write = outfile.write # Find start of encoded data while 1: s = readline() if not s: raise ValueError, 'Missing "begin" line in input data' if s[:5] == 'begin': break # Decode while 1: s = readline() if not s or \ s == 'end\n': break try: data = a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = a2b_uu(s[:nbytes]) #sys.stderr.write("Warning: %s\n" % str(v)) write(data) if not s: raise ValueError, 'Truncated input data' return (outfile.getvalue(), len(input)) class Codec(codecs.Codec): def encode(self,input,errors='strict'): return uu_encode(input,errors) def decode(self,input,errors='strict'): return uu_decode(input,errors) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (uu_encode,uu_decode,StreamReader,StreamWriter)
Python
""" Python 'undefined' Codec This codec will always raise a ValueError exception when being used. It is intended for use by the site.py file to switch off automatic string to Unicode coercion. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): raise UnicodeError, "undefined encoding" def decode(self,input,errors='strict'): raise UnicodeError, "undefined encoding" class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-10.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a2: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x00a3: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x00a4: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00a5: 0x0128, # LATIN CAPITAL LETTER I WITH TILDE 0x00a6: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00a8: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00a9: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00aa: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00ab: 0x0166, # LATIN CAPITAL LETTER T WITH STROKE 0x00ac: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00ae: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00af: 0x014a, # LATIN CAPITAL LETTER ENG 0x00b1: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00b2: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x00b3: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x00b4: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x00b5: 0x0129, # LATIN SMALL LETTER I WITH TILDE 0x00b6: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00b8: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00b9: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00ba: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00bb: 0x0167, # LATIN SMALL LETTER T WITH STROKE 0x00bc: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00bd: 0x2015, # HORIZONTAL BAR 0x00be: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00bf: 0x014b, # LATIN SMALL LETTER ENG 0x00c0: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x00c7: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00c8: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ca: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00cc: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x00d1: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00d2: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00d7: 0x0168, # LATIN CAPITAL LETTER U WITH TILDE 0x00d9: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00e0: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x00e7: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00e8: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ea: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00ec: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x00f1: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00f2: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x00f7: 0x0169, # LATIN SMALL LETTER U WITH TILDE 0x00f9: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00ff: 0x0138, # LATIN SMALL LETTER KRA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP860.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x008c: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x008e: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x008f: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x0092: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x0099: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00a2, # CENT SIGN 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x009e: 0x20a7, # PESETA SIGN 0x009f: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-11.TXT' with gencodec.py. Generated from mapping found in ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/8859-11.TXT """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0e01, # THAI CHARACTER KO KAI 0x00a2: 0x0e02, # THAI CHARACTER KHO KHAI 0x00a3: 0x0e03, # THAI CHARACTER KHO KHUAT 0x00a4: 0x0e04, # THAI CHARACTER KHO KHWAI 0x00a5: 0x0e05, # THAI CHARACTER KHO KHON 0x00a6: 0x0e06, # THAI CHARACTER KHO RAKHANG 0x00a7: 0x0e07, # THAI CHARACTER NGO NGU 0x00a8: 0x0e08, # THAI CHARACTER CHO CHAN 0x00a9: 0x0e09, # THAI CHARACTER CHO CHING 0x00aa: 0x0e0a, # THAI CHARACTER CHO CHANG 0x00ab: 0x0e0b, # THAI CHARACTER SO SO 0x00ac: 0x0e0c, # THAI CHARACTER CHO CHOE 0x00ad: 0x0e0d, # THAI CHARACTER YO YING 0x00ae: 0x0e0e, # THAI CHARACTER DO CHADA 0x00af: 0x0e0f, # THAI CHARACTER TO PATAK 0x00b0: 0x0e10, # THAI CHARACTER THO THAN 0x00b1: 0x0e11, # THAI CHARACTER THO NANGMONTHO 0x00b2: 0x0e12, # THAI CHARACTER THO PHUTHAO 0x00b3: 0x0e13, # THAI CHARACTER NO NEN 0x00b4: 0x0e14, # THAI CHARACTER DO DEK 0x00b5: 0x0e15, # THAI CHARACTER TO TAO 0x00b6: 0x0e16, # THAI CHARACTER THO THUNG 0x00b7: 0x0e17, # THAI CHARACTER THO THAHAN 0x00b8: 0x0e18, # THAI CHARACTER THO THONG 0x00b9: 0x0e19, # THAI CHARACTER NO NU 0x00ba: 0x0e1a, # THAI CHARACTER BO BAIMAI 0x00bb: 0x0e1b, # THAI CHARACTER PO PLA 0x00bc: 0x0e1c, # THAI CHARACTER PHO PHUNG 0x00bd: 0x0e1d, # THAI CHARACTER FO FA 0x00be: 0x0e1e, # THAI CHARACTER PHO PHAN 0x00bf: 0x0e1f, # THAI CHARACTER FO FAN 0x00c0: 0x0e20, # THAI CHARACTER PHO SAMPHAO 0x00c1: 0x0e21, # THAI CHARACTER MO MA 0x00c2: 0x0e22, # THAI CHARACTER YO YAK 0x00c3: 0x0e23, # THAI CHARACTER RO RUA 0x00c4: 0x0e24, # THAI CHARACTER RU 0x00c5: 0x0e25, # THAI CHARACTER LO LING 0x00c6: 0x0e26, # THAI CHARACTER LU 0x00c7: 0x0e27, # THAI CHARACTER WO WAEN 0x00c8: 0x0e28, # THAI CHARACTER SO SALA 0x00c9: 0x0e29, # THAI CHARACTER SO RUSI 0x00ca: 0x0e2a, # THAI CHARACTER SO SUA 0x00cb: 0x0e2b, # THAI CHARACTER HO HIP 0x00cc: 0x0e2c, # THAI CHARACTER LO CHULA 0x00cd: 0x0e2d, # THAI CHARACTER O ANG 0x00ce: 0x0e2e, # THAI CHARACTER HO NOKHUK 0x00cf: 0x0e2f, # THAI CHARACTER PAIYANNOI 0x00d0: 0x0e30, # THAI CHARACTER SARA A 0x00d1: 0x0e31, # THAI CHARACTER MAI HAN-AKAT 0x00d2: 0x0e32, # THAI CHARACTER SARA AA 0x00d3: 0x0e33, # THAI CHARACTER SARA AM 0x00d4: 0x0e34, # THAI CHARACTER SARA I 0x00d5: 0x0e35, # THAI CHARACTER SARA II 0x00d6: 0x0e36, # THAI CHARACTER SARA UE 0x00d7: 0x0e37, # THAI CHARACTER SARA UEE 0x00d8: 0x0e38, # THAI CHARACTER SARA U 0x00d9: 0x0e39, # THAI CHARACTER SARA UU 0x00da: 0x0e3a, # THAI CHARACTER PHINTHU 0x00db: None, 0x00dc: None, 0x00dd: None, 0x00de: None, 0x00df: 0x0e3f, # THAI CURRENCY SYMBOL BAHT 0x00e0: 0x0e40, # THAI CHARACTER SARA E 0x00e1: 0x0e41, # THAI CHARACTER SARA AE 0x00e2: 0x0e42, # THAI CHARACTER SARA O 0x00e3: 0x0e43, # THAI CHARACTER SARA AI MAIMUAN 0x00e4: 0x0e44, # THAI CHARACTER SARA AI MAIMALAI 0x00e5: 0x0e45, # THAI CHARACTER LAKKHANGYAO 0x00e6: 0x0e46, # THAI CHARACTER MAIYAMOK 0x00e7: 0x0e47, # THAI CHARACTER MAITAIKHU 0x00e8: 0x0e48, # THAI CHARACTER MAI EK 0x00e9: 0x0e49, # THAI CHARACTER MAI THO 0x00ea: 0x0e4a, # THAI CHARACTER MAI TRI 0x00eb: 0x0e4b, # THAI CHARACTER MAI CHATTAWA 0x00ec: 0x0e4c, # THAI CHARACTER THANTHAKHAT 0x00ed: 0x0e4d, # THAI CHARACTER NIKHAHIT 0x00ee: 0x0e4e, # THAI CHARACTER YAMAKKAN 0x00ef: 0x0e4f, # THAI CHARACTER FONGMAN 0x00f0: 0x0e50, # THAI DIGIT ZERO 0x00f1: 0x0e51, # THAI DIGIT ONE 0x00f2: 0x0e52, # THAI DIGIT TWO 0x00f3: 0x0e53, # THAI DIGIT THREE 0x00f4: 0x0e54, # THAI DIGIT FOUR 0x00f5: 0x0e55, # THAI DIGIT FIVE 0x00f6: 0x0e56, # THAI DIGIT SIX 0x00f7: 0x0e57, # THAI DIGIT SEVEN 0x00f8: 0x0e58, # THAI DIGIT EIGHT 0x00f9: 0x0e59, # THAI DIGIT NINE 0x00fa: 0x0e5a, # THAI CHARACTER ANGKHANKHU 0x00fb: 0x0e5b, # THAI CHARACTER KHOMUT 0x00fc: None, 0x00fd: None, 0x00fe: None, 0x00ff: None, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'hex_codec' Codec - 2-digit hex content transfer encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (mal@lemburg.com). """ import codecs, binascii ### Codec APIs def hex_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = binascii.b2a_hex(input) return (output, len(input)) def hex_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = binascii.a2b_hex(input) return (output, len(input)) class Codec(codecs.Codec): def encode(self, input,errors='strict'): return hex_encode(input,errors) def decode(self, input,errors='strict'): return hex_decode(input,errors) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (hex_encode,hex_decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1255.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: None, # UNDEFINED 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: None, # UNDEFINED 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: None, # UNDEFINED 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: None, # UNDEFINED 0x009d: None, # UNDEFINED 0x009e: None, # UNDEFINED 0x009f: None, # UNDEFINED 0x00a4: 0x20aa, # NEW SHEQEL SIGN 0x00aa: 0x00d7, # MULTIPLICATION SIGN 0x00ba: 0x00f7, # DIVISION SIGN 0x00c0: 0x05b0, # HEBREW POINT SHEVA 0x00c1: 0x05b1, # HEBREW POINT HATAF SEGOL 0x00c2: 0x05b2, # HEBREW POINT HATAF PATAH 0x00c3: 0x05b3, # HEBREW POINT HATAF QAMATS 0x00c4: 0x05b4, # HEBREW POINT HIRIQ 0x00c5: 0x05b5, # HEBREW POINT TSERE 0x00c6: 0x05b6, # HEBREW POINT SEGOL 0x00c7: 0x05b7, # HEBREW POINT PATAH 0x00c8: 0x05b8, # HEBREW POINT QAMATS 0x00c9: 0x05b9, # HEBREW POINT HOLAM 0x00ca: None, # UNDEFINED 0x00cb: 0x05bb, # HEBREW POINT QUBUTS 0x00cc: 0x05bc, # HEBREW POINT DAGESH OR MAPIQ 0x00cd: 0x05bd, # HEBREW POINT METEG 0x00ce: 0x05be, # HEBREW PUNCTUATION MAQAF 0x00cf: 0x05bf, # HEBREW POINT RAFE 0x00d0: 0x05c0, # HEBREW PUNCTUATION PASEQ 0x00d1: 0x05c1, # HEBREW POINT SHIN DOT 0x00d2: 0x05c2, # HEBREW POINT SIN DOT 0x00d3: 0x05c3, # HEBREW PUNCTUATION SOF PASUQ 0x00d4: 0x05f0, # HEBREW LIGATURE YIDDISH DOUBLE VAV 0x00d5: 0x05f1, # HEBREW LIGATURE YIDDISH VAV YOD 0x00d6: 0x05f2, # HEBREW LIGATURE YIDDISH DOUBLE YOD 0x00d7: 0x05f3, # HEBREW PUNCTUATION GERESH 0x00d8: 0x05f4, # HEBREW PUNCTUATION GERSHAYIM 0x00d9: None, # UNDEFINED 0x00da: None, # UNDEFINED 0x00db: None, # UNDEFINED 0x00dc: None, # UNDEFINED 0x00dd: None, # UNDEFINED 0x00de: None, # UNDEFINED 0x00df: None, # UNDEFINED 0x00e0: 0x05d0, # HEBREW LETTER ALEF 0x00e1: 0x05d1, # HEBREW LETTER BET 0x00e2: 0x05d2, # HEBREW LETTER GIMEL 0x00e3: 0x05d3, # HEBREW LETTER DALET 0x00e4: 0x05d4, # HEBREW LETTER HE 0x00e5: 0x05d5, # HEBREW LETTER VAV 0x00e6: 0x05d6, # HEBREW LETTER ZAYIN 0x00e7: 0x05d7, # HEBREW LETTER HET 0x00e8: 0x05d8, # HEBREW LETTER TET 0x00e9: 0x05d9, # HEBREW LETTER YOD 0x00ea: 0x05da, # HEBREW LETTER FINAL KAF 0x00eb: 0x05db, # HEBREW LETTER KAF 0x00ec: 0x05dc, # HEBREW LETTER LAMED 0x00ed: 0x05dd, # HEBREW LETTER FINAL MEM 0x00ee: 0x05de, # HEBREW LETTER MEM 0x00ef: 0x05df, # HEBREW LETTER FINAL NUN 0x00f0: 0x05e0, # HEBREW LETTER NUN 0x00f1: 0x05e1, # HEBREW LETTER SAMEKH 0x00f2: 0x05e2, # HEBREW LETTER AYIN 0x00f3: 0x05e3, # HEBREW LETTER FINAL PE 0x00f4: 0x05e4, # HEBREW LETTER PE 0x00f5: 0x05e5, # HEBREW LETTER FINAL TSADI 0x00f6: 0x05e6, # HEBREW LETTER TSADI 0x00f7: 0x05e7, # HEBREW LETTER QOF 0x00f8: 0x05e8, # HEBREW LETTER RESH 0x00f9: 0x05e9, # HEBREW LETTER SHIN 0x00fa: 0x05ea, # HEBREW LETTER TAV 0x00fb: None, # UNDEFINED 0x00fc: None, # UNDEFINED 0x00fd: 0x200e, # LEFT-TO-RIGHT MARK 0x00fe: 0x200f, # RIGHT-TO-LEFT MARK 0x00ff: None, # UNDEFINED }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'raw-unicode-escape' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = staticmethod(codecs.raw_unicode_escape_encode) decode = staticmethod(codecs.raw_unicode_escape_decode) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP875.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0004: 0x009c, # CONTROL 0x0005: 0x0009, # HORIZONTAL TABULATION 0x0006: 0x0086, # CONTROL 0x0007: 0x007f, # DELETE 0x0008: 0x0097, # CONTROL 0x0009: 0x008d, # CONTROL 0x000a: 0x008e, # CONTROL 0x0014: 0x009d, # CONTROL 0x0015: 0x0085, # CONTROL 0x0016: 0x0008, # BACKSPACE 0x0017: 0x0087, # CONTROL 0x001a: 0x0092, # CONTROL 0x001b: 0x008f, # CONTROL 0x0020: 0x0080, # CONTROL 0x0021: 0x0081, # CONTROL 0x0022: 0x0082, # CONTROL 0x0023: 0x0083, # CONTROL 0x0024: 0x0084, # CONTROL 0x0025: 0x000a, # LINE FEED 0x0026: 0x0017, # END OF TRANSMISSION BLOCK 0x0027: 0x001b, # ESCAPE 0x0028: 0x0088, # CONTROL 0x0029: 0x0089, # CONTROL 0x002a: 0x008a, # CONTROL 0x002b: 0x008b, # CONTROL 0x002c: 0x008c, # CONTROL 0x002d: 0x0005, # ENQUIRY 0x002e: 0x0006, # ACKNOWLEDGE 0x002f: 0x0007, # BELL 0x0030: 0x0090, # CONTROL 0x0031: 0x0091, # CONTROL 0x0032: 0x0016, # SYNCHRONOUS IDLE 0x0033: 0x0093, # CONTROL 0x0034: 0x0094, # CONTROL 0x0035: 0x0095, # CONTROL 0x0036: 0x0096, # CONTROL 0x0037: 0x0004, # END OF TRANSMISSION 0x0038: 0x0098, # CONTROL 0x0039: 0x0099, # CONTROL 0x003a: 0x009a, # CONTROL 0x003b: 0x009b, # CONTROL 0x003c: 0x0014, # DEVICE CONTROL FOUR 0x003d: 0x0015, # NEGATIVE ACKNOWLEDGE 0x003e: 0x009e, # CONTROL 0x003f: 0x001a, # SUBSTITUTE 0x0040: 0x0020, # SPACE 0x0041: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x0042: 0x0392, # GREEK CAPITAL LETTER BETA 0x0043: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x0044: 0x0394, # GREEK CAPITAL LETTER DELTA 0x0045: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x0046: 0x0396, # GREEK CAPITAL LETTER ZETA 0x0047: 0x0397, # GREEK CAPITAL LETTER ETA 0x0048: 0x0398, # GREEK CAPITAL LETTER THETA 0x0049: 0x0399, # GREEK CAPITAL LETTER IOTA 0x004a: 0x005b, # LEFT SQUARE BRACKET 0x004b: 0x002e, # FULL STOP 0x004c: 0x003c, # LESS-THAN SIGN 0x004d: 0x0028, # LEFT PARENTHESIS 0x004e: 0x002b, # PLUS SIGN 0x004f: 0x0021, # EXCLAMATION MARK 0x0050: 0x0026, # AMPERSAND 0x0051: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x0052: 0x039b, # GREEK CAPITAL LETTER LAMDA 0x0053: 0x039c, # GREEK CAPITAL LETTER MU 0x0054: 0x039d, # GREEK CAPITAL LETTER NU 0x0055: 0x039e, # GREEK CAPITAL LETTER XI 0x0056: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x0057: 0x03a0, # GREEK CAPITAL LETTER PI 0x0058: 0x03a1, # GREEK CAPITAL LETTER RHO 0x0059: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x005a: 0x005d, # RIGHT SQUARE BRACKET 0x005b: 0x0024, # DOLLAR SIGN 0x005c: 0x002a, # ASTERISK 0x005d: 0x0029, # RIGHT PARENTHESIS 0x005e: 0x003b, # SEMICOLON 0x005f: 0x005e, # CIRCUMFLEX ACCENT 0x0060: 0x002d, # HYPHEN-MINUS 0x0061: 0x002f, # SOLIDUS 0x0062: 0x03a4, # GREEK CAPITAL LETTER TAU 0x0063: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x0064: 0x03a6, # GREEK CAPITAL LETTER PHI 0x0065: 0x03a7, # GREEK CAPITAL LETTER CHI 0x0066: 0x03a8, # GREEK CAPITAL LETTER PSI 0x0067: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x0068: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x0069: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x006a: 0x007c, # VERTICAL LINE 0x006b: 0x002c, # COMMA 0x006c: 0x0025, # PERCENT SIGN 0x006d: 0x005f, # LOW LINE 0x006e: 0x003e, # GREATER-THAN SIGN 0x006f: 0x003f, # QUESTION MARK 0x0070: 0x00a8, # DIAERESIS 0x0071: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x0072: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x0073: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x0074: 0x00a0, # NO-BREAK SPACE 0x0075: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x0076: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x0077: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x0078: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x0079: 0x0060, # GRAVE ACCENT 0x007a: 0x003a, # COLON 0x007b: 0x0023, # NUMBER SIGN 0x007c: 0x0040, # COMMERCIAL AT 0x007d: 0x0027, # APOSTROPHE 0x007e: 0x003d, # EQUALS SIGN 0x007f: 0x0022, # QUOTATION MARK 0x0080: 0x0385, # GREEK DIALYTIKA TONOS 0x0081: 0x0061, # LATIN SMALL LETTER A 0x0082: 0x0062, # LATIN SMALL LETTER B 0x0083: 0x0063, # LATIN SMALL LETTER C 0x0084: 0x0064, # LATIN SMALL LETTER D 0x0085: 0x0065, # LATIN SMALL LETTER E 0x0086: 0x0066, # LATIN SMALL LETTER F 0x0087: 0x0067, # LATIN SMALL LETTER G 0x0088: 0x0068, # LATIN SMALL LETTER H 0x0089: 0x0069, # LATIN SMALL LETTER I 0x008a: 0x03b1, # GREEK SMALL LETTER ALPHA 0x008b: 0x03b2, # GREEK SMALL LETTER BETA 0x008c: 0x03b3, # GREEK SMALL LETTER GAMMA 0x008d: 0x03b4, # GREEK SMALL LETTER DELTA 0x008e: 0x03b5, # GREEK SMALL LETTER EPSILON 0x008f: 0x03b6, # GREEK SMALL LETTER ZETA 0x0090: 0x00b0, # DEGREE SIGN 0x0091: 0x006a, # LATIN SMALL LETTER J 0x0092: 0x006b, # LATIN SMALL LETTER K 0x0093: 0x006c, # LATIN SMALL LETTER L 0x0094: 0x006d, # LATIN SMALL LETTER M 0x0095: 0x006e, # LATIN SMALL LETTER N 0x0096: 0x006f, # LATIN SMALL LETTER O 0x0097: 0x0070, # LATIN SMALL LETTER P 0x0098: 0x0071, # LATIN SMALL LETTER Q 0x0099: 0x0072, # LATIN SMALL LETTER R 0x009a: 0x03b7, # GREEK SMALL LETTER ETA 0x009b: 0x03b8, # GREEK SMALL LETTER THETA 0x009c: 0x03b9, # GREEK SMALL LETTER IOTA 0x009d: 0x03ba, # GREEK SMALL LETTER KAPPA 0x009e: 0x03bb, # GREEK SMALL LETTER LAMDA 0x009f: 0x03bc, # GREEK SMALL LETTER MU 0x00a0: 0x00b4, # ACUTE ACCENT 0x00a1: 0x007e, # TILDE 0x00a2: 0x0073, # LATIN SMALL LETTER S 0x00a3: 0x0074, # LATIN SMALL LETTER T 0x00a4: 0x0075, # LATIN SMALL LETTER U 0x00a5: 0x0076, # LATIN SMALL LETTER V 0x00a6: 0x0077, # LATIN SMALL LETTER W 0x00a7: 0x0078, # LATIN SMALL LETTER X 0x00a8: 0x0079, # LATIN SMALL LETTER Y 0x00a9: 0x007a, # LATIN SMALL LETTER Z 0x00aa: 0x03bd, # GREEK SMALL LETTER NU 0x00ab: 0x03be, # GREEK SMALL LETTER XI 0x00ac: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00ad: 0x03c0, # GREEK SMALL LETTER PI 0x00ae: 0x03c1, # GREEK SMALL LETTER RHO 0x00af: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00b0: 0x00a3, # POUND SIGN 0x00b1: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x00b2: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x00b3: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x00b4: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00b5: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00b6: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00b7: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00b8: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00b9: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00ba: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00bb: 0x03c4, # GREEK SMALL LETTER TAU 0x00bc: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00bd: 0x03c6, # GREEK SMALL LETTER PHI 0x00be: 0x03c7, # GREEK SMALL LETTER CHI 0x00bf: 0x03c8, # GREEK SMALL LETTER PSI 0x00c0: 0x007b, # LEFT CURLY BRACKET 0x00c1: 0x0041, # LATIN CAPITAL LETTER A 0x00c2: 0x0042, # LATIN CAPITAL LETTER B 0x00c3: 0x0043, # LATIN CAPITAL LETTER C 0x00c4: 0x0044, # LATIN CAPITAL LETTER D 0x00c5: 0x0045, # LATIN CAPITAL LETTER E 0x00c6: 0x0046, # LATIN CAPITAL LETTER F 0x00c7: 0x0047, # LATIN CAPITAL LETTER G 0x00c8: 0x0048, # LATIN CAPITAL LETTER H 0x00c9: 0x0049, # LATIN CAPITAL LETTER I 0x00ca: 0x00ad, # SOFT HYPHEN 0x00cb: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00cc: 0x0390, # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x00cd: 0x03b0, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x00ce: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00cf: 0x2015, # HORIZONTAL BAR 0x00d0: 0x007d, # RIGHT CURLY BRACKET 0x00d1: 0x004a, # LATIN CAPITAL LETTER J 0x00d2: 0x004b, # LATIN CAPITAL LETTER K 0x00d3: 0x004c, # LATIN CAPITAL LETTER L 0x00d4: 0x004d, # LATIN CAPITAL LETTER M 0x00d5: 0x004e, # LATIN CAPITAL LETTER N 0x00d6: 0x004f, # LATIN CAPITAL LETTER O 0x00d7: 0x0050, # LATIN CAPITAL LETTER P 0x00d8: 0x0051, # LATIN CAPITAL LETTER Q 0x00d9: 0x0052, # LATIN CAPITAL LETTER R 0x00da: 0x00b1, # PLUS-MINUS SIGN 0x00db: 0x00bd, # VULGAR FRACTION ONE HALF 0x00dc: 0x001a, # SUBSTITUTE 0x00dd: 0x0387, # GREEK ANO TELEIA 0x00de: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00df: 0x00a6, # BROKEN BAR 0x00e0: 0x005c, # REVERSE SOLIDUS 0x00e1: 0x001a, # SUBSTITUTE 0x00e2: 0x0053, # LATIN CAPITAL LETTER S 0x00e3: 0x0054, # LATIN CAPITAL LETTER T 0x00e4: 0x0055, # LATIN CAPITAL LETTER U 0x00e5: 0x0056, # LATIN CAPITAL LETTER V 0x00e6: 0x0057, # LATIN CAPITAL LETTER W 0x00e7: 0x0058, # LATIN CAPITAL LETTER X 0x00e8: 0x0059, # LATIN CAPITAL LETTER Y 0x00e9: 0x005a, # LATIN CAPITAL LETTER Z 0x00ea: 0x00b2, # SUPERSCRIPT TWO 0x00eb: 0x00a7, # SECTION SIGN 0x00ec: 0x001a, # SUBSTITUTE 0x00ed: 0x001a, # SUBSTITUTE 0x00ee: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ef: 0x00ac, # NOT SIGN 0x00f0: 0x0030, # DIGIT ZERO 0x00f1: 0x0031, # DIGIT ONE 0x00f2: 0x0032, # DIGIT TWO 0x00f3: 0x0033, # DIGIT THREE 0x00f4: 0x0034, # DIGIT FOUR 0x00f5: 0x0035, # DIGIT FIVE 0x00f6: 0x0036, # DIGIT SIX 0x00f7: 0x0037, # DIGIT SEVEN 0x00f8: 0x0038, # DIGIT EIGHT 0x00f9: 0x0039, # DIGIT NINE 0x00fa: 0x00b3, # SUPERSCRIPT THREE 0x00fb: 0x00a9, # COPYRIGHT SIGN 0x00fc: 0x001a, # SUBSTITUTE 0x00fd: 0x001a, # SUBSTITUTE 0x00fe: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ff: 0x009f, # CONTROL }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Encoding Aliases Support This module is used by the encodings package search function to map encodings names to module names. Note that the search function normalizes the encoding names before doing the lookup, so the mapping will have to map normalized encoding names to module names. Contents: The following aliases dictionary contains mappings of all IANA character set names for which the Python core library provides codecs. In addition to these, a few Python specific codec aliases have also been added. """ aliases = { # Please keep this list sorted alphabetically by value ! # ascii codec '646' : 'ascii', 'ansi_x3.4_1968' : 'ascii', 'ansi_x3_4_1968' : 'ascii', # some email headers use this non-standard name 'ansi_x3.4_1986' : 'ascii', 'cp367' : 'ascii', 'csascii' : 'ascii', 'ibm367' : 'ascii', 'iso646_us' : 'ascii', 'iso_646.irv_1991' : 'ascii', 'iso_ir_6' : 'ascii', 'us' : 'ascii', 'us_ascii' : 'ascii', # base64_codec codec 'base64' : 'base64_codec', 'base_64' : 'base64_codec', # big5 codec 'big5_tw' : 'big5', 'csbig5' : 'big5', # big5hkscs codec 'big5_hkscs' : 'big5hkscs', 'hkscs' : 'big5hkscs', # bz2_codec codec 'bz2' : 'bz2_codec', # cp037 codec '037' : 'cp037', 'csibm037' : 'cp037', 'ebcdic_cp_ca' : 'cp037', 'ebcdic_cp_nl' : 'cp037', 'ebcdic_cp_us' : 'cp037', 'ebcdic_cp_wt' : 'cp037', 'ibm037' : 'cp037', 'ibm039' : 'cp037', # cp1026 codec '1026' : 'cp1026', 'csibm1026' : 'cp1026', 'ibm1026' : 'cp1026', # cp1140 codec '1140' : 'cp1140', 'ibm1140' : 'cp1140', # cp1250 codec '1250' : 'cp1250', 'windows_1250' : 'cp1250', # cp1251 codec '1251' : 'cp1251', 'windows_1251' : 'cp1251', # cp1252 codec '1252' : 'cp1252', 'windows_1252' : 'cp1252', # cp1253 codec '1253' : 'cp1253', 'windows_1253' : 'cp1253', # cp1254 codec '1254' : 'cp1254', 'windows_1254' : 'cp1254', # cp1255 codec '1255' : 'cp1255', 'windows_1255' : 'cp1255', # cp1256 codec '1256' : 'cp1256', 'windows_1256' : 'cp1256', # cp1257 codec '1257' : 'cp1257', 'windows_1257' : 'cp1257', # cp1258 codec '1258' : 'cp1258', 'windows_1258' : 'cp1258', # cp424 codec '424' : 'cp424', 'csibm424' : 'cp424', 'ebcdic_cp_he' : 'cp424', 'ibm424' : 'cp424', # cp437 codec '437' : 'cp437', 'cspc8codepage437' : 'cp437', 'ibm437' : 'cp437', # cp500 codec '500' : 'cp500', 'csibm500' : 'cp500', 'ebcdic_cp_be' : 'cp500', 'ebcdic_cp_ch' : 'cp500', 'ibm500' : 'cp500', # cp775 codec '775' : 'cp775', 'cspc775baltic' : 'cp775', 'ibm775' : 'cp775', # cp850 codec '850' : 'cp850', 'cspc850multilingual' : 'cp850', 'ibm850' : 'cp850', # cp852 codec '852' : 'cp852', 'cspcp852' : 'cp852', 'ibm852' : 'cp852', # cp855 codec '855' : 'cp855', 'csibm855' : 'cp855', 'ibm855' : 'cp855', # cp857 codec '857' : 'cp857', 'csibm857' : 'cp857', 'ibm857' : 'cp857', # cp860 codec '860' : 'cp860', 'csibm860' : 'cp860', 'ibm860' : 'cp860', # cp861 codec '861' : 'cp861', 'cp_is' : 'cp861', 'csibm861' : 'cp861', 'ibm861' : 'cp861', # cp862 codec '862' : 'cp862', 'cspc862latinhebrew' : 'cp862', 'ibm862' : 'cp862', # cp863 codec '863' : 'cp863', 'csibm863' : 'cp863', 'ibm863' : 'cp863', # cp864 codec '864' : 'cp864', 'csibm864' : 'cp864', 'ibm864' : 'cp864', # cp865 codec '865' : 'cp865', 'csibm865' : 'cp865', 'ibm865' : 'cp865', # cp866 codec '866' : 'cp866', 'csibm866' : 'cp866', 'ibm866' : 'cp866', # cp869 codec '869' : 'cp869', 'cp_gr' : 'cp869', 'csibm869' : 'cp869', 'ibm869' : 'cp869', # cp932 codec '932' : 'cp932', 'ms932' : 'cp932', 'mskanji' : 'cp932', 'ms_kanji' : 'cp932', # cp949 codec '949' : 'cp949', 'ms949' : 'cp949', 'uhc' : 'cp949', # cp950 codec '950' : 'cp950', 'ms950' : 'cp950', # euc_jis_2004 codec 'jisx0213' : 'euc_jis_2004', 'eucjis2004' : 'euc_jis_2004', 'euc_jis2004' : 'euc_jis_2004', # euc_jisx0213 codec 'eucjisx0213' : 'euc_jisx0213', # euc_jp codec 'eucjp' : 'euc_jp', 'ujis' : 'euc_jp', 'u_jis' : 'euc_jp', # euc_kr codec 'euckr' : 'euc_kr', 'korean' : 'euc_kr', 'ksc5601' : 'euc_kr', 'ks_c_5601' : 'euc_kr', 'ks_c_5601_1987' : 'euc_kr', 'ksx1001' : 'euc_kr', 'ks_x_1001' : 'euc_kr', # gb18030 codec 'gb18030_2000' : 'gb18030', # gb2312 codec 'chinese' : 'gb2312', 'csiso58gb231280' : 'gb2312', 'euc_cn' : 'gb2312', 'euccn' : 'gb2312', 'eucgb2312_cn' : 'gb2312', 'gb2312_1980' : 'gb2312', 'gb2312_80' : 'gb2312', 'iso_ir_58' : 'gb2312', # gbk codec '936' : 'gbk', 'cp936' : 'gbk', 'ms936' : 'gbk', # hex_codec codec 'hex' : 'hex_codec', # hp_roman8 codec 'roman8' : 'hp_roman8', 'r8' : 'hp_roman8', 'csHPRoman8' : 'hp_roman8', # hz codec 'hzgb' : 'hz', 'hz_gb' : 'hz', 'hz_gb_2312' : 'hz', # iso2022_jp codec 'csiso2022jp' : 'iso2022_jp', 'iso2022jp' : 'iso2022_jp', 'iso_2022_jp' : 'iso2022_jp', # iso2022_jp_1 codec 'iso2022jp_1' : 'iso2022_jp_1', 'iso_2022_jp_1' : 'iso2022_jp_1', # iso2022_jp_2 codec 'iso2022jp_2' : 'iso2022_jp_2', 'iso_2022_jp_2' : 'iso2022_jp_2', # iso2022_jp_2004 codec 'iso_2022_jp_2004' : 'iso2022_jp_2004', 'iso2022jp_2004' : 'iso2022_jp_2004', # iso2022_jp_3 codec 'iso2022jp_3' : 'iso2022_jp_3', 'iso_2022_jp_3' : 'iso2022_jp_3', # iso2022_jp_ext codec 'iso2022jp_ext' : 'iso2022_jp_ext', 'iso_2022_jp_ext' : 'iso2022_jp_ext', # iso2022_kr codec 'csiso2022kr' : 'iso2022_kr', 'iso2022kr' : 'iso2022_kr', 'iso_2022_kr' : 'iso2022_kr', # iso8859_10 codec 'csisolatin6' : 'iso8859_10', 'iso_8859_10' : 'iso8859_10', 'iso_8859_10_1992' : 'iso8859_10', 'iso_ir_157' : 'iso8859_10', 'l6' : 'iso8859_10', 'latin6' : 'iso8859_10', # iso8859_13 codec 'iso_8859_13' : 'iso8859_13', # iso8859_14 codec 'iso_8859_14' : 'iso8859_14', 'iso_8859_14_1998' : 'iso8859_14', 'iso_celtic' : 'iso8859_14', 'iso_ir_199' : 'iso8859_14', 'l8' : 'iso8859_14', 'latin8' : 'iso8859_14', # iso8859_15 codec 'iso_8859_15' : 'iso8859_15', # iso8859_2 codec 'csisolatin2' : 'iso8859_2', 'iso_8859_2' : 'iso8859_2', 'iso_8859_2_1987' : 'iso8859_2', 'iso_ir_101' : 'iso8859_2', 'l2' : 'iso8859_2', 'latin2' : 'iso8859_2', # iso8859_3 codec 'csisolatin3' : 'iso8859_3', 'iso_8859_3' : 'iso8859_3', 'iso_8859_3_1988' : 'iso8859_3', 'iso_ir_109' : 'iso8859_3', 'l3' : 'iso8859_3', 'latin3' : 'iso8859_3', # iso8859_4 codec 'csisolatin4' : 'iso8859_4', 'iso_8859_4' : 'iso8859_4', 'iso_8859_4_1988' : 'iso8859_4', 'iso_ir_110' : 'iso8859_4', 'l4' : 'iso8859_4', 'latin4' : 'iso8859_4', # iso8859_5 codec 'csisolatincyrillic' : 'iso8859_5', 'cyrillic' : 'iso8859_5', 'iso_8859_5' : 'iso8859_5', 'iso_8859_5_1988' : 'iso8859_5', 'iso_ir_144' : 'iso8859_5', # iso8859_6 codec 'arabic' : 'iso8859_6', 'asmo_708' : 'iso8859_6', 'csisolatinarabic' : 'iso8859_6', 'ecma_114' : 'iso8859_6', 'iso_8859_6' : 'iso8859_6', 'iso_8859_6_1987' : 'iso8859_6', 'iso_ir_127' : 'iso8859_6', # iso8859_7 codec 'csisolatingreek' : 'iso8859_7', 'ecma_118' : 'iso8859_7', 'elot_928' : 'iso8859_7', 'greek' : 'iso8859_7', 'greek8' : 'iso8859_7', 'iso_8859_7' : 'iso8859_7', 'iso_8859_7_1987' : 'iso8859_7', 'iso_ir_126' : 'iso8859_7', # iso8859_8 codec 'csisolatinhebrew' : 'iso8859_8', 'hebrew' : 'iso8859_8', 'iso_8859_8' : 'iso8859_8', 'iso_8859_8_1988' : 'iso8859_8', 'iso_ir_138' : 'iso8859_8', # iso8859_9 codec 'csisolatin5' : 'iso8859_9', 'iso_8859_9' : 'iso8859_9', 'iso_8859_9_1989' : 'iso8859_9', 'iso_ir_148' : 'iso8859_9', 'l5' : 'iso8859_9', 'latin5' : 'iso8859_9', # iso8859_11 codec 'thai' : 'iso8859_11', 'iso_8859_11' : 'iso8859_11', 'iso_8859_11_2001' : 'iso8859_11', # iso8859_16 codec 'iso_8859_16' : 'iso8859_16', 'iso_8859_16_2001' : 'iso8859_16', 'iso_ir_226' : 'iso8859_16', 'l10' : 'iso8859_16', 'latin10' : 'iso8859_16', # johab codec 'cp1361' : 'johab', 'ms1361' : 'johab', # koi8_r codec 'cskoi8r' : 'koi8_r', # latin_1 codec '8859' : 'latin_1', 'cp819' : 'latin_1', 'csisolatin1' : 'latin_1', 'ibm819' : 'latin_1', 'iso8859' : 'latin_1', 'iso_8859_1' : 'latin_1', 'iso_8859_1_1987' : 'latin_1', 'iso_ir_100' : 'latin_1', 'l1' : 'latin_1', 'latin' : 'latin_1', 'latin1' : 'latin_1', # mac_cyrillic codec 'maccyrillic' : 'mac_cyrillic', # mac_greek codec 'macgreek' : 'mac_greek', # mac_iceland codec 'maciceland' : 'mac_iceland', # mac_latin2 codec 'maccentraleurope' : 'mac_latin2', 'maclatin2' : 'mac_latin2', # mac_roman codec 'macroman' : 'mac_roman', # mac_turkish codec 'macturkish' : 'mac_turkish', # mbcs codec 'dbcs' : 'mbcs', # ptcp154 codec 'csptcp154' : 'ptcp154', 'pt154' : 'ptcp154', 'cp154' : 'ptcp154', 'cyrillic-asian' : 'ptcp154', # quopri_codec codec 'quopri' : 'quopri_codec', 'quoted_printable' : 'quopri_codec', 'quotedprintable' : 'quopri_codec', # rot_13 codec 'rot13' : 'rot_13', # shift_jis codec 'csshiftjis' : 'shift_jis', 'shiftjis' : 'shift_jis', 'sjis' : 'shift_jis', 's_jis' : 'shift_jis', # shift_jis_2004 codec 'shiftjis2004' : 'shift_jis_2004', 'sjis_2004' : 'shift_jis_2004', 's_jis_2004' : 'shift_jis_2004', # shift_jisx0213 codec 'shiftjisx0213' : 'shift_jisx0213', 'sjisx0213' : 'shift_jisx0213', 's_jisx0213' : 'shift_jisx0213', # tactis codec 'tis260' : 'tactis', # tis_620 codec 'tis620' : 'tis_620', 'tis_620_0' : 'tis_620', 'tis_620_2529_0' : 'tis_620', 'tis_620_2529_1' : 'tis_620', 'iso_ir_166' : 'tis_620', # utf_16 codec 'u16' : 'utf_16', 'utf16' : 'utf_16', # utf_16_be codec 'unicodebigunmarked' : 'utf_16_be', 'utf_16be' : 'utf_16_be', # utf_16_le codec 'unicodelittleunmarked' : 'utf_16_le', 'utf_16le' : 'utf_16_le', # utf_7 codec 'u7' : 'utf_7', 'utf7' : 'utf_7', # utf_8 codec 'u8' : 'utf_8', 'utf' : 'utf_8', 'utf8' : 'utf_8', 'utf8_ucs2' : 'utf_8', 'utf8_ucs4' : 'utf_8', # uu_codec codec 'uu' : 'uu_codec', # zlib_codec codec 'zip' : 'zlib_codec', 'zlib' : 'zlib_codec', }
Python
""" Python Character Mapping Codec generated from 'CP857.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x009f: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00a7: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x00ae, # REGISTERED SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00b8: 0x00a9, # COPYRIGHT SIGN 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x00a2, # CENT SIGN 0x00be: 0x00a5, # YEN SIGN 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x00c7: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00d1: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00d2: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00d5: None, # UNDEFINED 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x00a6, # BROKEN BAR 0x00de: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: None, # UNDEFINED 0x00e8: 0x00d7, # MULTIPLICATION SIGN 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00eb: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00ed: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00ee: 0x00af, # MACRON 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: None, # UNDEFINED 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x00b9, # SUPERSCRIPT ONE 0x00fc: 0x00b3, # SUPERSCRIPT THREE 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # iso2022_jp_2004.py: Python Unicode Codec for ISO2022_JP_2004 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: iso2022_jp_2004.py,v 1.1 2004/07/07 16:18:25 perky Exp $ # import _codecs_iso2022, codecs codec = _codecs_iso2022.getcodec('iso2022_jp_2004') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python 'unicode-escape' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = staticmethod(codecs.unicode_escape_encode) decode = staticmethod(codecs.unicode_escape_decode) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-6.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: None, 0x00a2: None, 0x00a3: None, 0x00a5: None, 0x00a6: None, 0x00a7: None, 0x00a8: None, 0x00a9: None, 0x00aa: None, 0x00ab: None, 0x00ac: 0x060c, # ARABIC COMMA 0x00ae: None, 0x00af: None, 0x00b0: None, 0x00b1: None, 0x00b2: None, 0x00b3: None, 0x00b4: None, 0x00b5: None, 0x00b6: None, 0x00b7: None, 0x00b8: None, 0x00b9: None, 0x00ba: None, 0x00bb: 0x061b, # ARABIC SEMICOLON 0x00bc: None, 0x00bd: None, 0x00be: None, 0x00bf: 0x061f, # ARABIC QUESTION MARK 0x00c0: None, 0x00c1: 0x0621, # ARABIC LETTER HAMZA 0x00c2: 0x0622, # ARABIC LETTER ALEF WITH MADDA ABOVE 0x00c3: 0x0623, # ARABIC LETTER ALEF WITH HAMZA ABOVE 0x00c4: 0x0624, # ARABIC LETTER WAW WITH HAMZA ABOVE 0x00c5: 0x0625, # ARABIC LETTER ALEF WITH HAMZA BELOW 0x00c6: 0x0626, # ARABIC LETTER YEH WITH HAMZA ABOVE 0x00c7: 0x0627, # ARABIC LETTER ALEF 0x00c8: 0x0628, # ARABIC LETTER BEH 0x00c9: 0x0629, # ARABIC LETTER TEH MARBUTA 0x00ca: 0x062a, # ARABIC LETTER TEH 0x00cb: 0x062b, # ARABIC LETTER THEH 0x00cc: 0x062c, # ARABIC LETTER JEEM 0x00cd: 0x062d, # ARABIC LETTER HAH 0x00ce: 0x062e, # ARABIC LETTER KHAH 0x00cf: 0x062f, # ARABIC LETTER DAL 0x00d0: 0x0630, # ARABIC LETTER THAL 0x00d1: 0x0631, # ARABIC LETTER REH 0x00d2: 0x0632, # ARABIC LETTER ZAIN 0x00d3: 0x0633, # ARABIC LETTER SEEN 0x00d4: 0x0634, # ARABIC LETTER SHEEN 0x00d5: 0x0635, # ARABIC LETTER SAD 0x00d6: 0x0636, # ARABIC LETTER DAD 0x00d7: 0x0637, # ARABIC LETTER TAH 0x00d8: 0x0638, # ARABIC LETTER ZAH 0x00d9: 0x0639, # ARABIC LETTER AIN 0x00da: 0x063a, # ARABIC LETTER GHAIN 0x00db: None, 0x00dc: None, 0x00dd: None, 0x00de: None, 0x00df: None, 0x00e0: 0x0640, # ARABIC TATWEEL 0x00e1: 0x0641, # ARABIC LETTER FEH 0x00e2: 0x0642, # ARABIC LETTER QAF 0x00e3: 0x0643, # ARABIC LETTER KAF 0x00e4: 0x0644, # ARABIC LETTER LAM 0x00e5: 0x0645, # ARABIC LETTER MEEM 0x00e6: 0x0646, # ARABIC LETTER NOON 0x00e7: 0x0647, # ARABIC LETTER HEH 0x00e8: 0x0648, # ARABIC LETTER WAW 0x00e9: 0x0649, # ARABIC LETTER ALEF MAKSURA 0x00ea: 0x064a, # ARABIC LETTER YEH 0x00eb: 0x064b, # ARABIC FATHATAN 0x00ec: 0x064c, # ARABIC DAMMATAN 0x00ed: 0x064d, # ARABIC KASRATAN 0x00ee: 0x064e, # ARABIC FATHA 0x00ef: 0x064f, # ARABIC DAMMA 0x00f0: 0x0650, # ARABIC KASRA 0x00f1: 0x0651, # ARABIC SHADDA 0x00f2: 0x0652, # ARABIC SUKUN 0x00f3: None, 0x00f4: None, 0x00f5: None, 0x00f6: None, 0x00f7: None, 0x00f8: None, 0x00f9: None, 0x00fa: None, 0x00fb: None, 0x00fc: None, 0x00fd: None, 0x00fe: None, 0x00ff: None, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-7.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00a2: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00a4: None, 0x00a5: None, 0x00aa: None, 0x00ae: None, 0x00af: 0x2015, # HORIZONTAL BAR 0x00b4: 0x0384, # GREEK TONOS 0x00b5: 0x0385, # GREEK DIALYTIKA TONOS 0x00b6: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x00b8: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x00b9: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x00ba: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x00bc: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x00be: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x00bf: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x00c0: 0x0390, # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x00c1: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x00c2: 0x0392, # GREEK CAPITAL LETTER BETA 0x00c3: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00c4: 0x0394, # GREEK CAPITAL LETTER DELTA 0x00c5: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x00c6: 0x0396, # GREEK CAPITAL LETTER ZETA 0x00c7: 0x0397, # GREEK CAPITAL LETTER ETA 0x00c8: 0x0398, # GREEK CAPITAL LETTER THETA 0x00c9: 0x0399, # GREEK CAPITAL LETTER IOTA 0x00ca: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x00cb: 0x039b, # GREEK CAPITAL LETTER LAMDA 0x00cc: 0x039c, # GREEK CAPITAL LETTER MU 0x00cd: 0x039d, # GREEK CAPITAL LETTER NU 0x00ce: 0x039e, # GREEK CAPITAL LETTER XI 0x00cf: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x00d0: 0x03a0, # GREEK CAPITAL LETTER PI 0x00d1: 0x03a1, # GREEK CAPITAL LETTER RHO 0x00d2: None, 0x00d3: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00d4: 0x03a4, # GREEK CAPITAL LETTER TAU 0x00d5: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x00d6: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00d7: 0x03a7, # GREEK CAPITAL LETTER CHI 0x00d8: 0x03a8, # GREEK CAPITAL LETTER PSI 0x00d9: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00da: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x00db: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x00dc: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x00dd: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x00de: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x00df: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00e0: 0x03b0, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x00e1: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e2: 0x03b2, # GREEK SMALL LETTER BETA 0x00e3: 0x03b3, # GREEK SMALL LETTER GAMMA 0x00e4: 0x03b4, # GREEK SMALL LETTER DELTA 0x00e5: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00e6: 0x03b6, # GREEK SMALL LETTER ZETA 0x00e7: 0x03b7, # GREEK SMALL LETTER ETA 0x00e8: 0x03b8, # GREEK SMALL LETTER THETA 0x00e9: 0x03b9, # GREEK SMALL LETTER IOTA 0x00ea: 0x03ba, # GREEK SMALL LETTER KAPPA 0x00eb: 0x03bb, # GREEK SMALL LETTER LAMDA 0x00ec: 0x03bc, # GREEK SMALL LETTER MU 0x00ed: 0x03bd, # GREEK SMALL LETTER NU 0x00ee: 0x03be, # GREEK SMALL LETTER XI 0x00ef: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00f0: 0x03c0, # GREEK SMALL LETTER PI 0x00f1: 0x03c1, # GREEK SMALL LETTER RHO 0x00f2: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00f3: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00f4: 0x03c4, # GREEK SMALL LETTER TAU 0x00f5: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00f6: 0x03c6, # GREEK SMALL LETTER PHI 0x00f7: 0x03c7, # GREEK SMALL LETTER CHI 0x00f8: 0x03c8, # GREEK SMALL LETTER PSI 0x00f9: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00fa: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00fb: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00fc: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00fd: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00fe: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00ff: None, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'utf-16-le' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs encode = codecs.utf_16_le_encode def decode(input, errors='strict'): return codecs.utf_16_le_decode(input, errors, True) class StreamWriter(codecs.StreamWriter): encode = codecs.utf_16_le_encode class StreamReader(codecs.StreamReader): decode = codecs.utf_16_le_decode ### encodings module API def getregentry(): return (encode,decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP863.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00b6, # PILCROW SIGN 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x2017, # DOUBLE LOW LINE 0x008e: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x008f: 0x00a7, # SECTION SIGN 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x0092: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x0095: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00a4, # CURRENCY SIGN 0x0099: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00a2, # CENT SIGN 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x009e: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00a6, # BROKEN BAR 0x00a1: 0x00b4, # ACUTE ACCENT 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00a8, # DIAERESIS 0x00a5: 0x00b8, # CEDILLA 0x00a6: 0x00b3, # SUPERSCRIPT THREE 0x00a7: 0x00af, # MACRON 0x00a8: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00a9: 0x2310, # REVERSED NOT SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-16.TXT' with gencodec.py. Generated from mapping found in ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/8859-16.TXT """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a2: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00a3: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00a4: 0x20ac, # EURO SIGN 0x00a5: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00a6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00a8: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00aa: 0x0218, # LATIN CAPITAL LETTER S WITH COMMA BELOW 0x00ac: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x00ae: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00af: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00b2: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00b3: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x00b4: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00b5: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00b8: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00b9: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ba: 0x0219, # LATIN SMALL LETTER S WITH COMMA BELOW 0x00bc: 0x0152, # LATIN CAPITAL LIGATURE OE 0x00bd: 0x0153, # LATIN SMALL LIGATURE OE 0x00be: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00bf: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00c3: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c5: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x00d0: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d1: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00d5: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x00d7: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x00d8: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00dd: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00de: 0x021a, # LATIN CAPITAL LETTER T WITH COMMA BELOW 0x00e3: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00e5: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x00f0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00f1: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00f5: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x00f7: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x00f8: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fd: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00fe: 0x021b, # LATIN SMALL LETTER T WITH COMMA BELOW }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'utf-8' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs encode = codecs.utf_8_encode def decode(input, errors='strict'): return codecs.utf_8_decode(input, errors, True) class StreamWriter(codecs.StreamWriter): encode = codecs.utf_8_encode class StreamReader(codecs.StreamReader): decode = codecs.utf_8_decode ### encodings module API def getregentry(): return (encode,decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP869.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: None, # UNDEFINED 0x0081: None, # UNDEFINED 0x0082: None, # UNDEFINED 0x0083: None, # UNDEFINED 0x0084: None, # UNDEFINED 0x0085: None, # UNDEFINED 0x0086: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x0087: None, # UNDEFINED 0x0088: 0x00b7, # MIDDLE DOT 0x0089: 0x00ac, # NOT SIGN 0x008a: 0x00a6, # BROKEN BAR 0x008b: 0x2018, # LEFT SINGLE QUOTATION MARK 0x008c: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x008d: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x008e: 0x2015, # HORIZONTAL BAR 0x008f: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x0090: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x0091: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x0092: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x0093: None, # UNDEFINED 0x0094: None, # UNDEFINED 0x0095: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x0096: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x0097: 0x00a9, # COPYRIGHT SIGN 0x0098: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x0099: 0x00b2, # SUPERSCRIPT TWO 0x009a: 0x00b3, # SUPERSCRIPT THREE 0x009b: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x009e: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x009f: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00a0: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00a1: 0x0390, # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x00a2: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00a3: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00a4: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x00a5: 0x0392, # GREEK CAPITAL LETTER BETA 0x00a6: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00a7: 0x0394, # GREEK CAPITAL LETTER DELTA 0x00a8: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x00a9: 0x0396, # GREEK CAPITAL LETTER ZETA 0x00aa: 0x0397, # GREEK CAPITAL LETTER ETA 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ad: 0x0399, # GREEK CAPITAL LETTER IOTA 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x00b6: 0x039b, # GREEK CAPITAL LETTER LAMDA 0x00b7: 0x039c, # GREEK CAPITAL LETTER MU 0x00b8: 0x039d, # GREEK CAPITAL LETTER NU 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x039e, # GREEK CAPITAL LETTER XI 0x00be: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x03a0, # GREEK CAPITAL LETTER PI 0x00c7: 0x03a1, # GREEK CAPITAL LETTER RHO 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00d0: 0x03a4, # GREEK CAPITAL LETTER TAU 0x00d1: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x00d2: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00d3: 0x03a7, # GREEK CAPITAL LETTER CHI 0x00d4: 0x03a8, # GREEK CAPITAL LETTER PSI 0x00d5: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00d6: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00d7: 0x03b2, # GREEK SMALL LETTER BETA 0x00d8: 0x03b3, # GREEK SMALL LETTER GAMMA 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x03b4, # GREEK SMALL LETTER DELTA 0x00de: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b6, # GREEK SMALL LETTER ZETA 0x00e1: 0x03b7, # GREEK SMALL LETTER ETA 0x00e2: 0x03b8, # GREEK SMALL LETTER THETA 0x00e3: 0x03b9, # GREEK SMALL LETTER IOTA 0x00e4: 0x03ba, # GREEK SMALL LETTER KAPPA 0x00e5: 0x03bb, # GREEK SMALL LETTER LAMDA 0x00e6: 0x03bc, # GREEK SMALL LETTER MU 0x00e7: 0x03bd, # GREEK SMALL LETTER NU 0x00e8: 0x03be, # GREEK SMALL LETTER XI 0x00e9: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00ea: 0x03c0, # GREEK SMALL LETTER PI 0x00eb: 0x03c1, # GREEK SMALL LETTER RHO 0x00ec: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00ed: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00ee: 0x03c4, # GREEK SMALL LETTER TAU 0x00ef: 0x0384, # GREEK TONOS 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00f3: 0x03c6, # GREEK SMALL LETTER PHI 0x00f4: 0x03c7, # GREEK SMALL LETTER CHI 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x03c8, # GREEK SMALL LETTER PSI 0x00f7: 0x0385, # GREEK DIALYTIKA TONOS 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00fb: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00fc: 0x03b0, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x00fd: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-8.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: None, 0x00aa: 0x00d7, # MULTIPLICATION SIGN 0x00ba: 0x00f7, # DIVISION SIGN 0x00bf: None, 0x00c0: None, 0x00c1: None, 0x00c2: None, 0x00c3: None, 0x00c4: None, 0x00c5: None, 0x00c6: None, 0x00c7: None, 0x00c8: None, 0x00c9: None, 0x00ca: None, 0x00cb: None, 0x00cc: None, 0x00cd: None, 0x00ce: None, 0x00cf: None, 0x00d0: None, 0x00d1: None, 0x00d2: None, 0x00d3: None, 0x00d4: None, 0x00d5: None, 0x00d6: None, 0x00d7: None, 0x00d8: None, 0x00d9: None, 0x00da: None, 0x00db: None, 0x00dc: None, 0x00dd: None, 0x00de: None, 0x00df: 0x2017, # DOUBLE LOW LINE 0x00e0: 0x05d0, # HEBREW LETTER ALEF 0x00e1: 0x05d1, # HEBREW LETTER BET 0x00e2: 0x05d2, # HEBREW LETTER GIMEL 0x00e3: 0x05d3, # HEBREW LETTER DALET 0x00e4: 0x05d4, # HEBREW LETTER HE 0x00e5: 0x05d5, # HEBREW LETTER VAV 0x00e6: 0x05d6, # HEBREW LETTER ZAYIN 0x00e7: 0x05d7, # HEBREW LETTER HET 0x00e8: 0x05d8, # HEBREW LETTER TET 0x00e9: 0x05d9, # HEBREW LETTER YOD 0x00ea: 0x05da, # HEBREW LETTER FINAL KAF 0x00eb: 0x05db, # HEBREW LETTER KAF 0x00ec: 0x05dc, # HEBREW LETTER LAMED 0x00ed: 0x05dd, # HEBREW LETTER FINAL MEM 0x00ee: 0x05de, # HEBREW LETTER MEM 0x00ef: 0x05df, # HEBREW LETTER FINAL NUN 0x00f0: 0x05e0, # HEBREW LETTER NUN 0x00f1: 0x05e1, # HEBREW LETTER SAMEKH 0x00f2: 0x05e2, # HEBREW LETTER AYIN 0x00f3: 0x05e3, # HEBREW LETTER FINAL PE 0x00f4: 0x05e4, # HEBREW LETTER PE 0x00f5: 0x05e5, # HEBREW LETTER FINAL TSADI 0x00f6: 0x05e6, # HEBREW LETTER TSADI 0x00f7: 0x05e7, # HEBREW LETTER QOF 0x00f8: 0x05e8, # HEBREW LETTER RESH 0x00f9: 0x05e9, # HEBREW LETTER SHIN 0x00fa: 0x05ea, # HEBREW LETTER TAV 0x00fb: None, 0x00fc: None, 0x00fd: 0x200e, # LEFT-TO-RIGHT MARK 0x00fe: 0x200f, # RIGHT-TO-LEFT MARK 0x00ff: None, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # euc_kr.py: Python Unicode Codec for EUC_KR # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: euc_kr.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_kr, codecs codec = _codecs_kr.getcodec('euc_kr') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-9.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00d0: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00dd: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x00de: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00f0: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00fd: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00fe: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # big5.py: Python Unicode Codec for BIG5 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: big5.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_tw, codecs codec = _codecs_tw.getcodec('big5') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python 'bz2_codec' Codec - bz2 compression encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Adapted by Raymond Hettinger from zlib_codec.py which was written by Marc-Andre Lemburg (mal@lemburg.com). """ import codecs import bz2 # this codec needs the optional bz2 module ! ### Codec APIs def bz2_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = bz2.compress(input) return (output, len(input)) def bz2_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = bz2.decompress(input) return (output, len(input)) class Codec(codecs.Codec): def encode(self, input, errors='strict'): return bz2_encode(input, errors) def decode(self, input, errors='strict'): return bz2_decode(input, errors) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (bz2_encode,bz2_decode,StreamReader,StreamWriter)
Python
# # iso2022_jp_1.py: Python Unicode Codec for ISO2022_JP_1 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: iso2022_jp_1.py,v 1.2 2004/06/28 18:16:03 perky Exp $ # import _codecs_iso2022, codecs codec = _codecs_iso2022.getcodec('iso2022_jp_1') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP1250.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: None, # UNDEFINED 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: None, # UNDEFINED 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x008d: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x008e: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x008f: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: None, # UNDEFINED 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x009d: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x009e: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x009f: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00a1: 0x02c7, # CARON 0x00a2: 0x02d8, # BREVE 0x00a3: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00a5: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00aa: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00af: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00b2: 0x02db, # OGONEK 0x00b3: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x00b9: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00ba: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00bc: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x00bd: 0x02dd, # DOUBLE ACUTE ACCENT 0x00be: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x00bf: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00c0: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00c3: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c5: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x00c6: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x00c8: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ca: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00cc: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x00cf: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x00d0: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d1: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00d2: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00d5: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x00d8: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00d9: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00db: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00de: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA 0x00e0: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00e3: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00e5: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x00e6: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x00e8: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ea: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00ec: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x00ef: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x00f0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00f1: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00f2: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00f5: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x00f8: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00f9: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fe: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA 0x00ff: 0x02d9, # DOT ABOVE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # johab.py: Python Unicode Codec for JOHAB # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: johab.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_kr, codecs codec = _codecs_kr.getcodec('johab') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec for cp1140 Written by Brian Quinlan(brian@sweetapp.com). NO WARRANTY. """ import codecs import copy import cp037 ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = copy.copy(cp037.decoding_map) decoding_map.update({ 0x009f: 0x20ac # EURO SIGN }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python 'base64_codec' Codec - base64 content transfer encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (mal@lemburg.com). """ import codecs, base64 ### Codec APIs def base64_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = base64.encodestring(input) return (output, len(input)) def base64_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = base64.decodestring(input) return (output, len(input)) class Codec(codecs.Codec): def encode(self, input,errors='strict'): return base64_encode(input,errors) def decode(self, input,errors='strict'): return base64_decode(input,errors) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (base64_encode,base64_decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP865.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x20a7, # PESETA SIGN 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x2310, # REVERSED NOT SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00a4, # CURRENCY SIGN 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'ROMAN.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0082: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x008c: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0093: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0096: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x0098: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x2020, # DAGGER 0x00a1: 0x00b0, # DEGREE SIGN 0x00a4: 0x00a7, # SECTION SIGN 0x00a5: 0x2022, # BULLET 0x00a6: 0x00b6, # PILCROW SIGN 0x00a7: 0x00df, # LATIN SMALL LETTER SHARP S 0x00a8: 0x00ae, # REGISTERED SIGN 0x00aa: 0x2122, # TRADE MARK SIGN 0x00ab: 0x00b4, # ACUTE ACCENT 0x00ac: 0x00a8, # DIAERESIS 0x00ad: 0x2260, # NOT EQUAL TO 0x00ae: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x00af: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x00b0: 0x221e, # INFINITY 0x00b2: 0x2264, # LESS-THAN OR EQUAL TO 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO 0x00b4: 0x00a5, # YEN SIGN 0x00b6: 0x2202, # PARTIAL DIFFERENTIAL 0x00b7: 0x2211, # N-ARY SUMMATION 0x00b8: 0x220f, # N-ARY PRODUCT 0x00b9: 0x03c0, # GREEK SMALL LETTER PI 0x00ba: 0x222b, # INTEGRAL 0x00bb: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00bc: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00bd: 0x2126, # OHM SIGN 0x00be: 0x00e6, # LATIN SMALL LIGATURE AE 0x00bf: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x00c0: 0x00bf, # INVERTED QUESTION MARK 0x00c1: 0x00a1, # INVERTED EXCLAMATION MARK 0x00c2: 0x00ac, # NOT SIGN 0x00c3: 0x221a, # SQUARE ROOT 0x00c4: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00c5: 0x2248, # ALMOST EQUAL TO 0x00c6: 0x2206, # INCREMENT 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS 0x00ca: 0x00a0, # NO-BREAK SPACE 0x00cb: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00cc: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00cd: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00ce: 0x0152, # LATIN CAPITAL LIGATURE OE 0x00cf: 0x0153, # LATIN SMALL LIGATURE OE 0x00d0: 0x2013, # EN DASH 0x00d1: 0x2014, # EM DASH 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00d6: 0x00f7, # DIVISION SIGN 0x00d7: 0x25ca, # LOZENGE 0x00d8: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00d9: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00da: 0x2044, # FRACTION SLASH 0x00db: 0x00a4, # CURRENCY SIGN 0x00dc: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x00dd: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x00de: 0xfb01, # LATIN SMALL LIGATURE FI 0x00df: 0xfb02, # LATIN SMALL LIGATURE FL 0x00e0: 0x2021, # DOUBLE DAGGER 0x00e1: 0x00b7, # MIDDLE DOT 0x00e2: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x00e3: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00e4: 0x2030, # PER MILLE SIGN 0x00e5: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00e6: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00e7: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00e8: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00e9: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00ea: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00eb: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00ec: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00ed: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00f0: None, # UNDEFINED 0x00f1: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00f2: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00f3: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00f4: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00f5: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00f6: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x00f7: 0x02dc, # SMALL TILDE 0x00f8: 0x00af, # MACRON 0x00f9: 0x02d8, # BREVE 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x02da, # RING ABOVE 0x00fc: 0x00b8, # CEDILLA 0x00fd: 0x02dd, # DOUBLE ACUTE ACCENT 0x00fe: 0x02db, # OGONEK 0x00ff: 0x02c7, # CARON }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'LATIN2.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x0082: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0088: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x0089: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x008c: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x008d: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x0090: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x0091: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0093: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x0094: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x0095: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x0096: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x0098: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x009d: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x009e: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x2020, # DAGGER 0x00a1: 0x00b0, # DEGREE SIGN 0x00a2: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00a4: 0x00a7, # SECTION SIGN 0x00a5: 0x2022, # BULLET 0x00a6: 0x00b6, # PILCROW SIGN 0x00a7: 0x00df, # LATIN SMALL LETTER SHARP S 0x00a8: 0x00ae, # REGISTERED SIGN 0x00aa: 0x2122, # TRADE MARK SIGN 0x00ab: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00ac: 0x00a8, # DIAERESIS 0x00ad: 0x2260, # NOT EQUAL TO 0x00ae: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x00af: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00b0: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00b1: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00b2: 0x2264, # LESS-THAN OR EQUAL TO 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO 0x00b4: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x00b5: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00b6: 0x2202, # PARTIAL DIFFERENTIAL 0x00b7: 0x2211, # N-ARY SUMMATION 0x00b8: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x00b9: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00ba: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00bb: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x00bc: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x00bd: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x00be: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x00bf: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00c0: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00c1: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00c2: 0x00ac, # NOT SIGN 0x00c3: 0x221a, # SQUARE ROOT 0x00c4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00c5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00c6: 0x2206, # INCREMENT 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS 0x00ca: 0x00a0, # NO-BREAK SPACE 0x00cb: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00cc: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x00cd: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00ce: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x00cf: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00d0: 0x2013, # EN DASH 0x00d1: 0x2014, # EM DASH 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00d6: 0x00f7, # DIVISION SIGN 0x00d7: 0x25ca, # LOZENGE 0x00d8: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x00d9: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00da: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00db: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00dc: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x00dd: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x00de: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00df: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA 0x00e0: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA 0x00e1: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00e2: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x00e3: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00e4: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00e5: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x00e6: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x00e7: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00e8: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x00e9: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x00ea: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00eb: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00ec: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00ed: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00f0: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00f1: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00f2: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00f3: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x00f4: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00f5: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00f6: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00f7: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00f8: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00f9: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00fa: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00fb: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00fc: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00fd: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00fe: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x00ff: 0x02c7, # CARON }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP1006.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x06f0, # EXTENDED ARABIC-INDIC DIGIT ZERO 0x00a2: 0x06f1, # EXTENDED ARABIC-INDIC DIGIT ONE 0x00a3: 0x06f2, # EXTENDED ARABIC-INDIC DIGIT TWO 0x00a4: 0x06f3, # EXTENDED ARABIC-INDIC DIGIT THREE 0x00a5: 0x06f4, # EXTENDED ARABIC-INDIC DIGIT FOUR 0x00a6: 0x06f5, # EXTENDED ARABIC-INDIC DIGIT FIVE 0x00a7: 0x06f6, # EXTENDED ARABIC-INDIC DIGIT SIX 0x00a8: 0x06f7, # EXTENDED ARABIC-INDIC DIGIT SEVEN 0x00a9: 0x06f8, # EXTENDED ARABIC-INDIC DIGIT EIGHT 0x00aa: 0x06f9, # EXTENDED ARABIC-INDIC DIGIT NINE 0x00ab: 0x060c, # ARABIC COMMA 0x00ac: 0x061b, # ARABIC SEMICOLON 0x00ae: 0x061f, # ARABIC QUESTION MARK 0x00af: 0xfe81, # ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM 0x00b0: 0xfe8d, # ARABIC LETTER ALEF ISOLATED FORM 0x00b1: 0xfe8e, # ARABIC LETTER ALEF FINAL FORM 0x00b2: 0xfe8e, # ARABIC LETTER ALEF FINAL FORM 0x00b3: 0xfe8f, # ARABIC LETTER BEH ISOLATED FORM 0x00b4: 0xfe91, # ARABIC LETTER BEH INITIAL FORM 0x00b5: 0xfb56, # ARABIC LETTER PEH ISOLATED FORM 0x00b6: 0xfb58, # ARABIC LETTER PEH INITIAL FORM 0x00b7: 0xfe93, # ARABIC LETTER TEH MARBUTA ISOLATED FORM 0x00b8: 0xfe95, # ARABIC LETTER TEH ISOLATED FORM 0x00b9: 0xfe97, # ARABIC LETTER TEH INITIAL FORM 0x00ba: 0xfb66, # ARABIC LETTER TTEH ISOLATED FORM 0x00bb: 0xfb68, # ARABIC LETTER TTEH INITIAL FORM 0x00bc: 0xfe99, # ARABIC LETTER THEH ISOLATED FORM 0x00bd: 0xfe9b, # ARABIC LETTER THEH INITIAL FORM 0x00be: 0xfe9d, # ARABIC LETTER JEEM ISOLATED FORM 0x00bf: 0xfe9f, # ARABIC LETTER JEEM INITIAL FORM 0x00c0: 0xfb7a, # ARABIC LETTER TCHEH ISOLATED FORM 0x00c1: 0xfb7c, # ARABIC LETTER TCHEH INITIAL FORM 0x00c2: 0xfea1, # ARABIC LETTER HAH ISOLATED FORM 0x00c3: 0xfea3, # ARABIC LETTER HAH INITIAL FORM 0x00c4: 0xfea5, # ARABIC LETTER KHAH ISOLATED FORM 0x00c5: 0xfea7, # ARABIC LETTER KHAH INITIAL FORM 0x00c6: 0xfea9, # ARABIC LETTER DAL ISOLATED FORM 0x00c7: 0xfb84, # ARABIC LETTER DAHAL ISOLATED FORMN 0x00c8: 0xfeab, # ARABIC LETTER THAL ISOLATED FORM 0x00c9: 0xfead, # ARABIC LETTER REH ISOLATED FORM 0x00ca: 0xfb8c, # ARABIC LETTER RREH ISOLATED FORM 0x00cb: 0xfeaf, # ARABIC LETTER ZAIN ISOLATED FORM 0x00cc: 0xfb8a, # ARABIC LETTER JEH ISOLATED FORM 0x00cd: 0xfeb1, # ARABIC LETTER SEEN ISOLATED FORM 0x00ce: 0xfeb3, # ARABIC LETTER SEEN INITIAL FORM 0x00cf: 0xfeb5, # ARABIC LETTER SHEEN ISOLATED FORM 0x00d0: 0xfeb7, # ARABIC LETTER SHEEN INITIAL FORM 0x00d1: 0xfeb9, # ARABIC LETTER SAD ISOLATED FORM 0x00d2: 0xfebb, # ARABIC LETTER SAD INITIAL FORM 0x00d3: 0xfebd, # ARABIC LETTER DAD ISOLATED FORM 0x00d4: 0xfebf, # ARABIC LETTER DAD INITIAL FORM 0x00d5: 0xfec1, # ARABIC LETTER TAH ISOLATED FORM 0x00d6: 0xfec5, # ARABIC LETTER ZAH ISOLATED FORM 0x00d7: 0xfec9, # ARABIC LETTER AIN ISOLATED FORM 0x00d8: 0xfeca, # ARABIC LETTER AIN FINAL FORM 0x00d9: 0xfecb, # ARABIC LETTER AIN INITIAL FORM 0x00da: 0xfecc, # ARABIC LETTER AIN MEDIAL FORM 0x00db: 0xfecd, # ARABIC LETTER GHAIN ISOLATED FORM 0x00dc: 0xfece, # ARABIC LETTER GHAIN FINAL FORM 0x00dd: 0xfecf, # ARABIC LETTER GHAIN INITIAL FORM 0x00de: 0xfed0, # ARABIC LETTER GHAIN MEDIAL FORM 0x00df: 0xfed1, # ARABIC LETTER FEH ISOLATED FORM 0x00e0: 0xfed3, # ARABIC LETTER FEH INITIAL FORM 0x00e1: 0xfed5, # ARABIC LETTER QAF ISOLATED FORM 0x00e2: 0xfed7, # ARABIC LETTER QAF INITIAL FORM 0x00e3: 0xfed9, # ARABIC LETTER KAF ISOLATED FORM 0x00e4: 0xfedb, # ARABIC LETTER KAF INITIAL FORM 0x00e5: 0xfb92, # ARABIC LETTER GAF ISOLATED FORM 0x00e6: 0xfb94, # ARABIC LETTER GAF INITIAL FORM 0x00e7: 0xfedd, # ARABIC LETTER LAM ISOLATED FORM 0x00e8: 0xfedf, # ARABIC LETTER LAM INITIAL FORM 0x00e9: 0xfee0, # ARABIC LETTER LAM MEDIAL FORM 0x00ea: 0xfee1, # ARABIC LETTER MEEM ISOLATED FORM 0x00eb: 0xfee3, # ARABIC LETTER MEEM INITIAL FORM 0x00ec: 0xfb9e, # ARABIC LETTER NOON GHUNNA ISOLATED FORM 0x00ed: 0xfee5, # ARABIC LETTER NOON ISOLATED FORM 0x00ee: 0xfee7, # ARABIC LETTER NOON INITIAL FORM 0x00ef: 0xfe85, # ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM 0x00f0: 0xfeed, # ARABIC LETTER WAW ISOLATED FORM 0x00f1: 0xfba6, # ARABIC LETTER HEH GOAL ISOLATED FORM 0x00f2: 0xfba8, # ARABIC LETTER HEH GOAL INITIAL FORM 0x00f3: 0xfba9, # ARABIC LETTER HEH GOAL MEDIAL FORM 0x00f4: 0xfbaa, # ARABIC LETTER HEH DOACHASHMEE ISOLATED FORM 0x00f5: 0xfe80, # ARABIC LETTER HAMZA ISOLATED FORM 0x00f6: 0xfe89, # ARABIC LETTER YEH WITH HAMZA ABOVE ISOLATED FORM 0x00f7: 0xfe8a, # ARABIC LETTER YEH WITH HAMZA ABOVE FINAL FORM 0x00f8: 0xfe8b, # ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM 0x00f9: 0xfef1, # ARABIC LETTER YEH ISOLATED FORM 0x00fa: 0xfef2, # ARABIC LETTER YEH FINAL FORM 0x00fb: 0xfef3, # ARABIC LETTER YEH INITIAL FORM 0x00fc: 0xfbb0, # ARABIC LETTER YEH BARREE WITH HAMZA ABOVE ISOLATED FORM 0x00fd: 0xfbae, # ARABIC LETTER YEH BARREE ISOLATED FORM 0x00fe: 0xfe7c, # ARABIC SHADDA ISOLATED FORM 0x00ff: 0xfe7d, # ARABIC SHADDA MEDIAL FORM }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Standard "encodings" Package Standard Python encoding modules are stored in this package directory. Codec modules must have names corresponding to normalized encoding names as defined in the normalize_encoding() function below, e.g. 'utf-8' must be implemented by the module 'utf_8.py'. Each codec module must export the following interface: * getregentry() -> (encoder, decoder, stream_reader, stream_writer) The getregentry() API must return callable objects which adhere to the Python Codec Interface Standard. In addition, a module may optionally also define the following APIs which are then used by the package's codec search function: * getaliases() -> sequence of encoding name strings to use as aliases Alias names returned by getaliases() must be normalized encoding names as defined by normalize_encoding(). Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" import codecs, exceptions, types, aliases _cache = {} _unknown = '--unknown--' _import_tail = ['*'] _norm_encoding_map = (' . ' '0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ' abcdefghijklmnopqrstuvwxyz ' ' ' ' ' ' ') _aliases = aliases.aliases class CodecRegistryError(exceptions.LookupError, exceptions.SystemError): pass def normalize_encoding(encoding): """ Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are collapsed and replaced with a single underscore, e.g. ' -;#' becomes '_'. Leading and trailing underscores are removed. Note that encoding names should be ASCII only; if they do use non-ASCII characters, these must be Latin-1 compatible. """ # Make sure we have an 8-bit string, because .translate() works # differently for Unicode strings. if type(encoding) is types.UnicodeType: # Note that .encode('latin-1') does *not* use the codec # registry, so this call doesn't recurse. (See unicodeobject.c # PyUnicode_AsEncodedString() for details) encoding = encoding.encode('latin-1') return '_'.join(encoding.translate(_norm_encoding_map).split()) def search_function(encoding): # Cache lookup entry = _cache.get(encoding, _unknown) if entry is not _unknown: return entry # Import the module: # # First try to find an alias for the normalized encoding # name and lookup the module using the aliased name, then try to # lookup the module using the standard import scheme, i.e. first # try in the encodings package, then at top-level. # norm_encoding = normalize_encoding(encoding) aliased_encoding = _aliases.get(norm_encoding) or \ _aliases.get(norm_encoding.replace('.', '_')) if aliased_encoding is not None: modnames = [aliased_encoding, norm_encoding] else: modnames = [norm_encoding] for modname in modnames: if not modname: continue try: mod = __import__(modname, globals(), locals(), _import_tail) except ImportError: pass else: break else: mod = None try: getregentry = mod.getregentry except AttributeError: # Not a codec module mod = None if mod is None: # Cache misses _cache[encoding] = None return None # Now ask the module for the registry entry entry = tuple(getregentry()) if len(entry) != 4: raise CodecRegistryError,\ 'module "%s" (%s) failed to register' % \ (mod.__name__, mod.__file__) for obj in entry: if not callable(obj): raise CodecRegistryError,\ 'incompatible codecs in module "%s" (%s)' % \ (mod.__name__, mod.__file__) # Cache the codec registry entry _cache[encoding] = entry # Register its aliases (without overwriting previously registered # aliases) try: codecaliases = mod.getaliases() except AttributeError: pass else: for alias in codecaliases: if not _aliases.has_key(alias): _aliases[alias] = modname # Return the registry entry return entry # Register the search_function in the Python codec registry codecs.register(search_function)
Python
""" Python Character Mapping Codec generated from '8859-1.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'KOI8-R.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x0081: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x0082: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x0083: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x0084: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x0085: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x0086: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x0087: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x0088: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x0089: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x008a: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x008b: 0x2580, # UPPER HALF BLOCK 0x008c: 0x2584, # LOWER HALF BLOCK 0x008d: 0x2588, # FULL BLOCK 0x008e: 0x258c, # LEFT HALF BLOCK 0x008f: 0x2590, # RIGHT HALF BLOCK 0x0090: 0x2591, # LIGHT SHADE 0x0091: 0x2592, # MEDIUM SHADE 0x0092: 0x2593, # DARK SHADE 0x0093: 0x2320, # TOP HALF INTEGRAL 0x0094: 0x25a0, # BLACK SQUARE 0x0095: 0x2219, # BULLET OPERATOR 0x0096: 0x221a, # SQUARE ROOT 0x0097: 0x2248, # ALMOST EQUAL TO 0x0098: 0x2264, # LESS-THAN OR EQUAL TO 0x0099: 0x2265, # GREATER-THAN OR EQUAL TO 0x009a: 0x00a0, # NO-BREAK SPACE 0x009b: 0x2321, # BOTTOM HALF INTEGRAL 0x009c: 0x00b0, # DEGREE SIGN 0x009d: 0x00b2, # SUPERSCRIPT TWO 0x009e: 0x00b7, # MIDDLE DOT 0x009f: 0x00f7, # DIVISION SIGN 0x00a0: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00a1: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00a2: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00a3: 0x0451, # CYRILLIC SMALL LETTER IO 0x00a4: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00a5: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00a6: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00a7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00a8: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00a9: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00aa: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00ab: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00ac: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00ad: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00ae: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00af: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00b0: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00b1: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00b2: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b3: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00b4: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b5: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00b6: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00b7: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00b8: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00b9: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00ba: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00bb: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00bc: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00bd: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00be: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00bf: 0x00a9, # COPYRIGHT SIGN 0x00c0: 0x044e, # CYRILLIC SMALL LETTER YU 0x00c1: 0x0430, # CYRILLIC SMALL LETTER A 0x00c2: 0x0431, # CYRILLIC SMALL LETTER BE 0x00c3: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00c4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00c5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00c6: 0x0444, # CYRILLIC SMALL LETTER EF 0x00c7: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00c8: 0x0445, # CYRILLIC SMALL LETTER HA 0x00c9: 0x0438, # CYRILLIC SMALL LETTER I 0x00ca: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00cb: 0x043a, # CYRILLIC SMALL LETTER KA 0x00cc: 0x043b, # CYRILLIC SMALL LETTER EL 0x00cd: 0x043c, # CYRILLIC SMALL LETTER EM 0x00ce: 0x043d, # CYRILLIC SMALL LETTER EN 0x00cf: 0x043e, # CYRILLIC SMALL LETTER O 0x00d0: 0x043f, # CYRILLIC SMALL LETTER PE 0x00d1: 0x044f, # CYRILLIC SMALL LETTER YA 0x00d2: 0x0440, # CYRILLIC SMALL LETTER ER 0x00d3: 0x0441, # CYRILLIC SMALL LETTER ES 0x00d4: 0x0442, # CYRILLIC SMALL LETTER TE 0x00d5: 0x0443, # CYRILLIC SMALL LETTER U 0x00d6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00d7: 0x0432, # CYRILLIC SMALL LETTER VE 0x00d8: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00d9: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00da: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00db: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00dc: 0x044d, # CYRILLIC SMALL LETTER E 0x00dd: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00de: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00df: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00e0: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x00e1: 0x0410, # CYRILLIC CAPITAL LETTER A 0x00e2: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x00e3: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x00e4: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x00e5: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x00e6: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x00e7: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x00e8: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x00e9: 0x0418, # CYRILLIC CAPITAL LETTER I 0x00ea: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x00eb: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x00ec: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x00ed: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x00ee: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x00ef: 0x041e, # CYRILLIC CAPITAL LETTER O 0x00f0: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x00f1: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00f2: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x00f3: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x00f4: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x00f5: 0x0423, # CYRILLIC CAPITAL LETTER U 0x00f6: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x00f7: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x00f8: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x00f9: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x00fa: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x00fb: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x00fc: 0x042d, # CYRILLIC CAPITAL LETTER E 0x00fd: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x00fe: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x00ff: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP1252.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x0089: 0x2030, # PER MILLE SIGN 0x008a: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE 0x008d: None, # UNDEFINED 0x008e: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x008f: None, # UNDEFINED 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x02dc, # SMALL TILDE 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: 0x0153, # LATIN SMALL LIGATURE OE 0x009d: None, # UNDEFINED 0x009e: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x009f: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'TURKISH.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0082: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x008c: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0093: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0096: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x0098: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x2020, # DAGGER 0x00a1: 0x00b0, # DEGREE SIGN 0x00a4: 0x00a7, # SECTION SIGN 0x00a5: 0x2022, # BULLET 0x00a6: 0x00b6, # PILCROW SIGN 0x00a7: 0x00df, # LATIN SMALL LETTER SHARP S 0x00a8: 0x00ae, # REGISTERED SIGN 0x00aa: 0x2122, # TRADE MARK SIGN 0x00ab: 0x00b4, # ACUTE ACCENT 0x00ac: 0x00a8, # DIAERESIS 0x00ad: 0x2260, # NOT EQUAL TO 0x00ae: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x00af: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x00b0: 0x221e, # INFINITY 0x00b2: 0x2264, # LESS-THAN OR EQUAL TO 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO 0x00b4: 0x00a5, # YEN SIGN 0x00b6: 0x2202, # PARTIAL DIFFERENTIAL 0x00b7: 0x2211, # N-ARY SUMMATION 0x00b8: 0x220f, # N-ARY PRODUCT 0x00b9: 0x03c0, # GREEK SMALL LETTER PI 0x00ba: 0x222b, # INTEGRAL 0x00bb: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00bc: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00bd: 0x2126, # OHM SIGN 0x00be: 0x00e6, # LATIN SMALL LIGATURE AE 0x00bf: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x00c0: 0x00bf, # INVERTED QUESTION MARK 0x00c1: 0x00a1, # INVERTED EXCLAMATION MARK 0x00c2: 0x00ac, # NOT SIGN 0x00c3: 0x221a, # SQUARE ROOT 0x00c4: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00c5: 0x2248, # ALMOST EQUAL TO 0x00c6: 0x2206, # INCREMENT 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS 0x00ca: 0x00a0, # NO-BREAK SPACE 0x00cb: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00cc: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00cd: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00ce: 0x0152, # LATIN CAPITAL LIGATURE OE 0x00cf: 0x0153, # LATIN SMALL LIGATURE OE 0x00d0: 0x2013, # EN DASH 0x00d1: 0x2014, # EM DASH 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00d6: 0x00f7, # DIVISION SIGN 0x00d7: 0x25ca, # LOZENGE 0x00d8: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00d9: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00da: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00db: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00dc: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x00dd: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00de: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00df: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00e0: 0x2021, # DOUBLE DAGGER 0x00e1: 0x00b7, # MIDDLE DOT 0x00e2: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x00e3: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00e4: 0x2030, # PER MILLE SIGN 0x00e5: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00e6: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00e7: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00e8: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00e9: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00ea: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00eb: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00ec: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00ed: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00f0: None, # UNDEFINED 0x00f1: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00f2: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00f3: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00f4: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00f5: None, # UNDEFINED 0x00f6: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x00f7: 0x02dc, # SMALL TILDE 0x00f8: 0x00af, # MACRON 0x00f9: 0x02d8, # BREVE 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x02da, # RING ABOVE 0x00fc: 0x00b8, # CEDILLA 0x00fd: 0x02dd, # DOUBLE ACUTE ACCENT 0x00fe: 0x02db, # OGONEK 0x00ff: 0x02c7, # CARON }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP1257.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x20ac, # EURO SIGN 0x0081: None, # UNDEFINED 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x0083: None, # UNDEFINED 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x2020, # DAGGER 0x0087: 0x2021, # DOUBLE DAGGER 0x0088: None, # UNDEFINED 0x0089: 0x2030, # PER MILLE SIGN 0x008a: None, # UNDEFINED 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x008c: None, # UNDEFINED 0x008d: 0x00a8, # DIAERESIS 0x008e: 0x02c7, # CARON 0x008f: 0x00b8, # CEDILLA 0x0090: None, # UNDEFINED 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: None, # UNDEFINED 0x0099: 0x2122, # TRADE MARK SIGN 0x009a: None, # UNDEFINED 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x009c: None, # UNDEFINED 0x009d: 0x00af, # MACRON 0x009e: 0x02db, # OGONEK 0x009f: None, # UNDEFINED 0x00a1: None, # UNDEFINED 0x00a5: None, # UNDEFINED 0x00a8: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x00aa: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA 0x00af: 0x00c6, # LATIN CAPITAL LETTER AE 0x00b8: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x00ba: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA 0x00bf: 0x00e6, # LATIN SMALL LETTER AE 0x00c0: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00c1: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00c2: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x00c3: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x00c6: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00c7: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x00c8: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ca: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x00cb: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x00cc: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x00cd: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00ce: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00cf: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00d0: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00d1: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00d2: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00d4: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00d8: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00d9: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00da: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x00db: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00dd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00de: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00e0: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00e1: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00e2: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x00e3: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x00e6: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00e7: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x00e8: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ea: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00eb: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x00ec: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x00ed: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00ee: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x00ef: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00f0: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00f1: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00f2: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00f4: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x00f8: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00f9: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x00fa: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x00fb: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00fd: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00fe: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00ff: 0x02d9, # DOT ABOVE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # gb2312.py: Python Unicode Codec for GB2312 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: gb2312.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_cn, codecs codec = _codecs_cn.getcodec('gb2312') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Generic Python Character Mapping Codec. Use this codec directly rather than through the automatic conversion mechanisms supplied by unicode() and .encode(). Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = staticmethod(codecs.charmap_encode) decode = staticmethod(codecs.charmap_decode) class StreamWriter(Codec,codecs.StreamWriter): def __init__(self,stream,errors='strict',mapping=None): codecs.StreamWriter.__init__(self,stream,errors) self.mapping = mapping def encode(self,input,errors='strict'): return Codec.encode(input,errors,self.mapping) class StreamReader(Codec,codecs.StreamReader): def __init__(self,stream,errors='strict',mapping=None): codecs.StreamReader.__init__(self,stream,errors) self.mapping = mapping def decode(self,input,errors='strict'): return Codec.decode(input,errors,self.mapping) ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP850.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x00ae, # REGISTERED SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00b8: 0x00a9, # COPYRIGHT SIGN 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x00a2, # CENT SIGN 0x00be: 0x00a5, # YEN SIGN 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x00c7: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x00f0, # LATIN SMALL LETTER ETH 0x00d1: 0x00d0, # LATIN CAPITAL LETTER ETH 0x00d2: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00d5: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x00a6, # BROKEN BAR 0x00de: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x00fe, # LATIN SMALL LETTER THORN 0x00e8: 0x00de, # LATIN CAPITAL LETTER THORN 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00eb: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ee: 0x00af, # MACRON 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2017, # DOUBLE LOW LINE 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x00b9, # SUPERSCRIPT ONE 0x00fc: 0x00b3, # SUPERSCRIPT THREE 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP737.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x0081: 0x0392, # GREEK CAPITAL LETTER BETA 0x0082: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x0083: 0x0394, # GREEK CAPITAL LETTER DELTA 0x0084: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x0085: 0x0396, # GREEK CAPITAL LETTER ZETA 0x0086: 0x0397, # GREEK CAPITAL LETTER ETA 0x0087: 0x0398, # GREEK CAPITAL LETTER THETA 0x0088: 0x0399, # GREEK CAPITAL LETTER IOTA 0x0089: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x008a: 0x039b, # GREEK CAPITAL LETTER LAMDA 0x008b: 0x039c, # GREEK CAPITAL LETTER MU 0x008c: 0x039d, # GREEK CAPITAL LETTER NU 0x008d: 0x039e, # GREEK CAPITAL LETTER XI 0x008e: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x008f: 0x03a0, # GREEK CAPITAL LETTER PI 0x0090: 0x03a1, # GREEK CAPITAL LETTER RHO 0x0091: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x0092: 0x03a4, # GREEK CAPITAL LETTER TAU 0x0093: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x0094: 0x03a6, # GREEK CAPITAL LETTER PHI 0x0095: 0x03a7, # GREEK CAPITAL LETTER CHI 0x0096: 0x03a8, # GREEK CAPITAL LETTER PSI 0x0097: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x0098: 0x03b1, # GREEK SMALL LETTER ALPHA 0x0099: 0x03b2, # GREEK SMALL LETTER BETA 0x009a: 0x03b3, # GREEK SMALL LETTER GAMMA 0x009b: 0x03b4, # GREEK SMALL LETTER DELTA 0x009c: 0x03b5, # GREEK SMALL LETTER EPSILON 0x009d: 0x03b6, # GREEK SMALL LETTER ZETA 0x009e: 0x03b7, # GREEK SMALL LETTER ETA 0x009f: 0x03b8, # GREEK SMALL LETTER THETA 0x00a0: 0x03b9, # GREEK SMALL LETTER IOTA 0x00a1: 0x03ba, # GREEK SMALL LETTER KAPPA 0x00a2: 0x03bb, # GREEK SMALL LETTER LAMDA 0x00a3: 0x03bc, # GREEK SMALL LETTER MU 0x00a4: 0x03bd, # GREEK SMALL LETTER NU 0x00a5: 0x03be, # GREEK SMALL LETTER XI 0x00a6: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00a7: 0x03c0, # GREEK SMALL LETTER PI 0x00a8: 0x03c1, # GREEK SMALL LETTER RHO 0x00a9: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00aa: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00ab: 0x03c4, # GREEK SMALL LETTER TAU 0x00ac: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00ad: 0x03c6, # GREEK SMALL LETTER PHI 0x00ae: 0x03c7, # GREEK SMALL LETTER CHI 0x00af: 0x03c8, # GREEK SMALL LETTER PSI 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00e1: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x00e2: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x00e3: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x00e4: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00e5: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00e6: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00e7: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00e8: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00e9: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00ea: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x00eb: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x00ec: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x00ed: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x00ee: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x00ef: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x00f0: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x00f5: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from '8859-4.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a2: 0x0138, # LATIN SMALL LETTER KRA 0x00a3: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA 0x00a5: 0x0128, # LATIN CAPITAL LETTER I WITH TILDE 0x00a6: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00a9: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00aa: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x00ab: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x00ac: 0x0166, # LATIN CAPITAL LETTER T WITH STROKE 0x00ae: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00b1: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00b2: 0x02db, # OGONEK 0x00b3: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA 0x00b5: 0x0129, # LATIN SMALL LETTER I WITH TILDE 0x00b6: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00b7: 0x02c7, # CARON 0x00b9: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00ba: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x00bb: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x00bc: 0x0167, # LATIN SMALL LETTER T WITH STROKE 0x00bd: 0x014a, # LATIN CAPITAL LETTER ENG 0x00be: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00bf: 0x014b, # LATIN SMALL LETTER ENG 0x00c0: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x00c7: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00c8: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ca: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00cc: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x00cf: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00d0: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d1: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00d2: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00d3: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00d9: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00dd: 0x0168, # LATIN CAPITAL LETTER U WITH TILDE 0x00de: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00e0: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x00e7: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00e8: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ea: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00ec: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x00ef: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x00f0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00f1: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00f2: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x00f3: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00f9: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00fd: 0x0169, # LATIN SMALL LETTER U WITH TILDE 0x00fe: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00ff: 0x02d9, # DOT ABOVE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # iso2022_jp_ext.py: Python Unicode Codec for ISO2022_JP_EXT # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: iso2022_jp_ext.py,v 1.2 2004/06/28 18:16:03 perky Exp $ # import _codecs_iso2022, codecs codec = _codecs_iso2022.getcodec('iso2022_jp_ext') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
# # cp950.py: Python Unicode Codec for CP950 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: cp950.py,v 1.8 2004/06/28 18:16:03 perky Exp $ # import _codecs_tw, codecs codec = _codecs_tw.getcodec('cp950') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python Character Mapping Codec generated from '8859-13.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00a5: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00a8: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x00aa: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA 0x00af: 0x00c6, # LATIN CAPITAL LETTER AE 0x00b4: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00b8: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x00ba: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA 0x00bf: 0x00e6, # LATIN SMALL LETTER AE 0x00c0: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00c1: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00c2: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x00c3: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x00c6: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00c7: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x00c8: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ca: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x00cb: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x00cc: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x00cd: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00ce: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00cf: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00d0: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00d1: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00d2: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00d4: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00d8: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00d9: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00da: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x00db: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00dd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00de: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00e0: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00e1: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00e2: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x00e3: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x00e6: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00e7: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x00e8: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00ea: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00eb: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x00ec: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x00ed: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00ee: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x00ef: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00f0: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00f1: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00f2: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00f4: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x00f8: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00f9: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x00fa: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x00fb: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00fd: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00fe: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00ff: 0x2019, # RIGHT SINGLE QUOTATION MARK }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'hp_roman8.txt' with gencodec.py. Based on data from ftp://dkuug.dk/i18n/charmaps/HP-ROMAN8 (Keld Simonsen) Original source: LaserJet IIP Printer User's Manual HP part no 33471-90901, Hewlet-Packard, June 1989. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x00a1: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00a2: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00a3: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00a4: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00a5: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00a6: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00a7: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00a8: 0x00b4, # ACUTE ACCENT 0x00a9: 0x02cb, # MODIFIER LETTER GRAVE ACCENT (Mandarin Chinese fourth tone) 0x00aa: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT 0x00ab: 0x00a8, # DIAERESIS 0x00ac: 0x02dc, # SMALL TILDE 0x00ad: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00ae: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00af: 0x20a4, # LIRA SIGN 0x00b0: 0x00af, # MACRON 0x00b1: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00b2: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00b3: 0x00b0, # DEGREE SIGN 0x00b4: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00b5: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x00b6: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00b7: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00b8: 0x00a1, # INVERTED EXCLAMATION MARK 0x00b9: 0x00bf, # INVERTED QUESTION MARK 0x00ba: 0x00a4, # CURRENCY SIGN 0x00bb: 0x00a3, # POUND SIGN 0x00bc: 0x00a5, # YEN SIGN 0x00bd: 0x00a7, # SECTION SIGN 0x00be: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00bf: 0x00a2, # CENT SIGN 0x00c0: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00c1: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00c2: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00c3: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00c4: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00c5: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x00c6: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00c7: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00c8: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x00c9: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x00ca: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x00cb: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x00cc: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x00cd: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ce: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x00cf: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00d0: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x00d1: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00d2: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x00d3: 0x00c6, # LATIN CAPITAL LETTER AE 0x00d4: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x00d5: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00d6: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x00d7: 0x00e6, # LATIN SMALL LETTER AE 0x00d8: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00d9: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x00da: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00db: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00dc: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x00dd: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x00de: 0x00df, # LATIN SMALL LETTER SHARP S (German) 0x00df: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e0: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00e1: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00e2: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x00e3: 0x00d0, # LATIN CAPITAL LETTER ETH (Icelandic) 0x00e4: 0x00f0, # LATIN SMALL LETTER ETH (Icelandic) 0x00e5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00e6: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00e7: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e8: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00e9: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00ea: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00eb: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00ec: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00ed: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ee: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS 0x00ef: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00f0: 0x00de, # LATIN CAPITAL LETTER THORN (Icelandic) 0x00f1: 0x00fe, # LATIN SMALL LETTER THORN (Icelandic) 0x00f2: 0x00b7, # MIDDLE DOT 0x00f3: 0x00b5, # MICRO SIGN 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f6: 0x2014, # EM DASH 0x00f7: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00f8: 0x00bd, # VULGAR FRACTION ONE HALF 0x00f9: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00fa: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00fb: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00fc: 0x25a0, # BLACK SQUARE 0x00fd: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00fe: 0x00b1, # PLUS-MINUS SIGN 0x00ff: None, }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
""" Python Character Mapping Codec generated from 'CP424.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0004: 0x009c, # SELECT 0x0005: 0x0009, # HORIZONTAL TABULATION 0x0006: 0x0086, # REQUIRED NEW LINE 0x0007: 0x007f, # DELETE 0x0008: 0x0097, # GRAPHIC ESCAPE 0x0009: 0x008d, # SUPERSCRIPT 0x000a: 0x008e, # REPEAT 0x0014: 0x009d, # RESTORE/ENABLE PRESENTATION 0x0015: 0x0085, # NEW LINE 0x0016: 0x0008, # BACKSPACE 0x0017: 0x0087, # PROGRAM OPERATOR COMMUNICATION 0x001a: 0x0092, # UNIT BACK SPACE 0x001b: 0x008f, # CUSTOMER USE ONE 0x0020: 0x0080, # DIGIT SELECT 0x0021: 0x0081, # START OF SIGNIFICANCE 0x0022: 0x0082, # FIELD SEPARATOR 0x0023: 0x0083, # WORD UNDERSCORE 0x0024: 0x0084, # BYPASS OR INHIBIT PRESENTATION 0x0025: 0x000a, # LINE FEED 0x0026: 0x0017, # END OF TRANSMISSION BLOCK 0x0027: 0x001b, # ESCAPE 0x0028: 0x0088, # SET ATTRIBUTE 0x0029: 0x0089, # START FIELD EXTENDED 0x002a: 0x008a, # SET MODE OR SWITCH 0x002b: 0x008b, # CONTROL SEQUENCE PREFIX 0x002c: 0x008c, # MODIFY FIELD ATTRIBUTE 0x002d: 0x0005, # ENQUIRY 0x002e: 0x0006, # ACKNOWLEDGE 0x002f: 0x0007, # BELL 0x0030: 0x0090, # <reserved> 0x0031: 0x0091, # <reserved> 0x0032: 0x0016, # SYNCHRONOUS IDLE 0x0033: 0x0093, # INDEX RETURN 0x0034: 0x0094, # PRESENTATION POSITION 0x0035: 0x0095, # TRANSPARENT 0x0036: 0x0096, # NUMERIC BACKSPACE 0x0037: 0x0004, # END OF TRANSMISSION 0x0038: 0x0098, # SUBSCRIPT 0x0039: 0x0099, # INDENT TABULATION 0x003a: 0x009a, # REVERSE FORM FEED 0x003b: 0x009b, # CUSTOMER USE THREE 0x003c: 0x0014, # DEVICE CONTROL FOUR 0x003d: 0x0015, # NEGATIVE ACKNOWLEDGE 0x003e: 0x009e, # <reserved> 0x003f: 0x001a, # SUBSTITUTE 0x0040: 0x0020, # SPACE 0x0041: 0x05d0, # HEBREW LETTER ALEF 0x0042: 0x05d1, # HEBREW LETTER BET 0x0043: 0x05d2, # HEBREW LETTER GIMEL 0x0044: 0x05d3, # HEBREW LETTER DALET 0x0045: 0x05d4, # HEBREW LETTER HE 0x0046: 0x05d5, # HEBREW LETTER VAV 0x0047: 0x05d6, # HEBREW LETTER ZAYIN 0x0048: 0x05d7, # HEBREW LETTER HET 0x0049: 0x05d8, # HEBREW LETTER TET 0x004a: 0x00a2, # CENT SIGN 0x004b: 0x002e, # FULL STOP 0x004c: 0x003c, # LESS-THAN SIGN 0x004d: 0x0028, # LEFT PARENTHESIS 0x004e: 0x002b, # PLUS SIGN 0x004f: 0x007c, # VERTICAL LINE 0x0050: 0x0026, # AMPERSAND 0x0051: 0x05d9, # HEBREW LETTER YOD 0x0052: 0x05da, # HEBREW LETTER FINAL KAF 0x0053: 0x05db, # HEBREW LETTER KAF 0x0054: 0x05dc, # HEBREW LETTER LAMED 0x0055: 0x05dd, # HEBREW LETTER FINAL MEM 0x0056: 0x05de, # HEBREW LETTER MEM 0x0057: 0x05df, # HEBREW LETTER FINAL NUN 0x0058: 0x05e0, # HEBREW LETTER NUN 0x0059: 0x05e1, # HEBREW LETTER SAMEKH 0x005a: 0x0021, # EXCLAMATION MARK 0x005b: 0x0024, # DOLLAR SIGN 0x005c: 0x002a, # ASTERISK 0x005d: 0x0029, # RIGHT PARENTHESIS 0x005e: 0x003b, # SEMICOLON 0x005f: 0x00ac, # NOT SIGN 0x0060: 0x002d, # HYPHEN-MINUS 0x0061: 0x002f, # SOLIDUS 0x0062: 0x05e2, # HEBREW LETTER AYIN 0x0063: 0x05e3, # HEBREW LETTER FINAL PE 0x0064: 0x05e4, # HEBREW LETTER PE 0x0065: 0x05e5, # HEBREW LETTER FINAL TSADI 0x0066: 0x05e6, # HEBREW LETTER TSADI 0x0067: 0x05e7, # HEBREW LETTER QOF 0x0068: 0x05e8, # HEBREW LETTER RESH 0x0069: 0x05e9, # HEBREW LETTER SHIN 0x006a: 0x00a6, # BROKEN BAR 0x006b: 0x002c, # COMMA 0x006c: 0x0025, # PERCENT SIGN 0x006d: 0x005f, # LOW LINE 0x006e: 0x003e, # GREATER-THAN SIGN 0x006f: 0x003f, # QUESTION MARK 0x0070: None, # UNDEFINED 0x0071: 0x05ea, # HEBREW LETTER TAV 0x0072: None, # UNDEFINED 0x0073: None, # UNDEFINED 0x0074: 0x00a0, # NO-BREAK SPACE 0x0075: None, # UNDEFINED 0x0076: None, # UNDEFINED 0x0077: None, # UNDEFINED 0x0078: 0x2017, # DOUBLE LOW LINE 0x0079: 0x0060, # GRAVE ACCENT 0x007a: 0x003a, # COLON 0x007b: 0x0023, # NUMBER SIGN 0x007c: 0x0040, # COMMERCIAL AT 0x007d: 0x0027, # APOSTROPHE 0x007e: 0x003d, # EQUALS SIGN 0x007f: 0x0022, # QUOTATION MARK 0x0080: None, # UNDEFINED 0x0081: 0x0061, # LATIN SMALL LETTER A 0x0082: 0x0062, # LATIN SMALL LETTER B 0x0083: 0x0063, # LATIN SMALL LETTER C 0x0084: 0x0064, # LATIN SMALL LETTER D 0x0085: 0x0065, # LATIN SMALL LETTER E 0x0086: 0x0066, # LATIN SMALL LETTER F 0x0087: 0x0067, # LATIN SMALL LETTER G 0x0088: 0x0068, # LATIN SMALL LETTER H 0x0089: 0x0069, # LATIN SMALL LETTER I 0x008a: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008b: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008c: None, # UNDEFINED 0x008d: None, # UNDEFINED 0x008e: None, # UNDEFINED 0x008f: 0x00b1, # PLUS-MINUS SIGN 0x0090: 0x00b0, # DEGREE SIGN 0x0091: 0x006a, # LATIN SMALL LETTER J 0x0092: 0x006b, # LATIN SMALL LETTER K 0x0093: 0x006c, # LATIN SMALL LETTER L 0x0094: 0x006d, # LATIN SMALL LETTER M 0x0095: 0x006e, # LATIN SMALL LETTER N 0x0096: 0x006f, # LATIN SMALL LETTER O 0x0097: 0x0070, # LATIN SMALL LETTER P 0x0098: 0x0071, # LATIN SMALL LETTER Q 0x0099: 0x0072, # LATIN SMALL LETTER R 0x009a: None, # UNDEFINED 0x009b: None, # UNDEFINED 0x009c: None, # UNDEFINED 0x009d: 0x00b8, # CEDILLA 0x009e: None, # UNDEFINED 0x009f: 0x00a4, # CURRENCY SIGN 0x00a0: 0x00b5, # MICRO SIGN 0x00a1: 0x007e, # TILDE 0x00a2: 0x0073, # LATIN SMALL LETTER S 0x00a3: 0x0074, # LATIN SMALL LETTER T 0x00a4: 0x0075, # LATIN SMALL LETTER U 0x00a5: 0x0076, # LATIN SMALL LETTER V 0x00a6: 0x0077, # LATIN SMALL LETTER W 0x00a7: 0x0078, # LATIN SMALL LETTER X 0x00a8: 0x0079, # LATIN SMALL LETTER Y 0x00a9: 0x007a, # LATIN SMALL LETTER Z 0x00aa: None, # UNDEFINED 0x00ab: None, # UNDEFINED 0x00ac: None, # UNDEFINED 0x00ad: None, # UNDEFINED 0x00ae: None, # UNDEFINED 0x00af: 0x00ae, # REGISTERED SIGN 0x00b0: 0x005e, # CIRCUMFLEX ACCENT 0x00b1: 0x00a3, # POUND SIGN 0x00b2: 0x00a5, # YEN SIGN 0x00b3: 0x00b7, # MIDDLE DOT 0x00b4: 0x00a9, # COPYRIGHT SIGN 0x00b5: 0x00a7, # SECTION SIGN 0x00b7: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00b8: 0x00bd, # VULGAR FRACTION ONE HALF 0x00b9: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00ba: 0x005b, # LEFT SQUARE BRACKET 0x00bb: 0x005d, # RIGHT SQUARE BRACKET 0x00bc: 0x00af, # MACRON 0x00bd: 0x00a8, # DIAERESIS 0x00be: 0x00b4, # ACUTE ACCENT 0x00bf: 0x00d7, # MULTIPLICATION SIGN 0x00c0: 0x007b, # LEFT CURLY BRACKET 0x00c1: 0x0041, # LATIN CAPITAL LETTER A 0x00c2: 0x0042, # LATIN CAPITAL LETTER B 0x00c3: 0x0043, # LATIN CAPITAL LETTER C 0x00c4: 0x0044, # LATIN CAPITAL LETTER D 0x00c5: 0x0045, # LATIN CAPITAL LETTER E 0x00c6: 0x0046, # LATIN CAPITAL LETTER F 0x00c7: 0x0047, # LATIN CAPITAL LETTER G 0x00c8: 0x0048, # LATIN CAPITAL LETTER H 0x00c9: 0x0049, # LATIN CAPITAL LETTER I 0x00ca: 0x00ad, # SOFT HYPHEN 0x00cb: None, # UNDEFINED 0x00cc: None, # UNDEFINED 0x00cd: None, # UNDEFINED 0x00ce: None, # UNDEFINED 0x00cf: None, # UNDEFINED 0x00d0: 0x007d, # RIGHT CURLY BRACKET 0x00d1: 0x004a, # LATIN CAPITAL LETTER J 0x00d2: 0x004b, # LATIN CAPITAL LETTER K 0x00d3: 0x004c, # LATIN CAPITAL LETTER L 0x00d4: 0x004d, # LATIN CAPITAL LETTER M 0x00d5: 0x004e, # LATIN CAPITAL LETTER N 0x00d6: 0x004f, # LATIN CAPITAL LETTER O 0x00d7: 0x0050, # LATIN CAPITAL LETTER P 0x00d8: 0x0051, # LATIN CAPITAL LETTER Q 0x00d9: 0x0052, # LATIN CAPITAL LETTER R 0x00da: 0x00b9, # SUPERSCRIPT ONE 0x00db: None, # UNDEFINED 0x00dc: None, # UNDEFINED 0x00dd: None, # UNDEFINED 0x00de: None, # UNDEFINED 0x00df: None, # UNDEFINED 0x00e0: 0x005c, # REVERSE SOLIDUS 0x00e1: 0x00f7, # DIVISION SIGN 0x00e2: 0x0053, # LATIN CAPITAL LETTER S 0x00e3: 0x0054, # LATIN CAPITAL LETTER T 0x00e4: 0x0055, # LATIN CAPITAL LETTER U 0x00e5: 0x0056, # LATIN CAPITAL LETTER V 0x00e6: 0x0057, # LATIN CAPITAL LETTER W 0x00e7: 0x0058, # LATIN CAPITAL LETTER X 0x00e8: 0x0059, # LATIN CAPITAL LETTER Y 0x00e9: 0x005a, # LATIN CAPITAL LETTER Z 0x00ea: 0x00b2, # SUPERSCRIPT TWO 0x00eb: None, # UNDEFINED 0x00ec: None, # UNDEFINED 0x00ed: None, # UNDEFINED 0x00ee: None, # UNDEFINED 0x00ef: None, # UNDEFINED 0x00f0: 0x0030, # DIGIT ZERO 0x00f1: 0x0031, # DIGIT ONE 0x00f2: 0x0032, # DIGIT TWO 0x00f3: 0x0033, # DIGIT THREE 0x00f4: 0x0034, # DIGIT FOUR 0x00f5: 0x0035, # DIGIT FIVE 0x00f6: 0x0036, # DIGIT SIX 0x00f7: 0x0037, # DIGIT SEVEN 0x00f8: 0x0038, # DIGIT EIGHT 0x00f9: 0x0039, # DIGIT NINE 0x00fa: 0x00b3, # SUPERSCRIPT THREE 0x00fb: None, # UNDEFINED 0x00fc: None, # UNDEFINED 0x00fd: None, # UNDEFINED 0x00fe: None, # UNDEFINED 0x00ff: 0x009f, # EIGHT ONES }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # euc_jis_2004.py: Python Unicode Codec for EUC_JIS_2004 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: euc_jis_2004.py,v 1.1 2004/07/07 16:18:25 perky Exp $ # import _codecs_jp, codecs codec = _codecs_jp.getcodec('euc_jis_2004') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
# # big5hkscs.py: Python Unicode Codec for BIG5HKSCS # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: big5hkscs.py,v 1.1 2004/06/29 05:14:27 perky Exp $ # import _codecs_hk, codecs codec = _codecs_hk.getcodec('big5hkscs') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
# # iso2022_jp.py: Python Unicode Codec for ISO2022_JP # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: iso2022_jp.py,v 1.2 2004/06/28 18:16:03 perky Exp $ # import _codecs_iso2022, codecs codec = _codecs_iso2022.getcodec('iso2022_jp') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
""" Python 'mbcs' Codec for Windows Cloned by Mark Hammond (mhammond@skippinet.com.au) from ascii.py, which was written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = staticmethod(codecs.mbcs_encode) decode = staticmethod(codecs.mbcs_decode) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass class StreamConverter(StreamWriter,StreamReader): encode = codecs.mbcs_decode decode = codecs.mbcs_encode ### encodings module API def getregentry(): return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
Python
""" Python Character Mapping Codec generated from 'CP500.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0004: 0x009c, # CONTROL 0x0005: 0x0009, # HORIZONTAL TABULATION 0x0006: 0x0086, # CONTROL 0x0007: 0x007f, # DELETE 0x0008: 0x0097, # CONTROL 0x0009: 0x008d, # CONTROL 0x000a: 0x008e, # CONTROL 0x0014: 0x009d, # CONTROL 0x0015: 0x0085, # CONTROL 0x0016: 0x0008, # BACKSPACE 0x0017: 0x0087, # CONTROL 0x001a: 0x0092, # CONTROL 0x001b: 0x008f, # CONTROL 0x0020: 0x0080, # CONTROL 0x0021: 0x0081, # CONTROL 0x0022: 0x0082, # CONTROL 0x0023: 0x0083, # CONTROL 0x0024: 0x0084, # CONTROL 0x0025: 0x000a, # LINE FEED 0x0026: 0x0017, # END OF TRANSMISSION BLOCK 0x0027: 0x001b, # ESCAPE 0x0028: 0x0088, # CONTROL 0x0029: 0x0089, # CONTROL 0x002a: 0x008a, # CONTROL 0x002b: 0x008b, # CONTROL 0x002c: 0x008c, # CONTROL 0x002d: 0x0005, # ENQUIRY 0x002e: 0x0006, # ACKNOWLEDGE 0x002f: 0x0007, # BELL 0x0030: 0x0090, # CONTROL 0x0031: 0x0091, # CONTROL 0x0032: 0x0016, # SYNCHRONOUS IDLE 0x0033: 0x0093, # CONTROL 0x0034: 0x0094, # CONTROL 0x0035: 0x0095, # CONTROL 0x0036: 0x0096, # CONTROL 0x0037: 0x0004, # END OF TRANSMISSION 0x0038: 0x0098, # CONTROL 0x0039: 0x0099, # CONTROL 0x003a: 0x009a, # CONTROL 0x003b: 0x009b, # CONTROL 0x003c: 0x0014, # DEVICE CONTROL FOUR 0x003d: 0x0015, # NEGATIVE ACKNOWLEDGE 0x003e: 0x009e, # CONTROL 0x003f: 0x001a, # SUBSTITUTE 0x0040: 0x0020, # SPACE 0x0041: 0x00a0, # NO-BREAK SPACE 0x0042: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0043: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0044: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0045: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0046: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x0047: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0048: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0049: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x004a: 0x005b, # LEFT SQUARE BRACKET 0x004b: 0x002e, # FULL STOP 0x004c: 0x003c, # LESS-THAN SIGN 0x004d: 0x0028, # LEFT PARENTHESIS 0x004e: 0x002b, # PLUS SIGN 0x004f: 0x0021, # EXCLAMATION MARK 0x0050: 0x0026, # AMPERSAND 0x0051: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0052: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0053: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0054: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0055: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0056: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0057: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0058: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x0059: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN) 0x005a: 0x005d, # RIGHT SQUARE BRACKET 0x005b: 0x0024, # DOLLAR SIGN 0x005c: 0x002a, # ASTERISK 0x005d: 0x0029, # RIGHT PARENTHESIS 0x005e: 0x003b, # SEMICOLON 0x005f: 0x005e, # CIRCUMFLEX ACCENT 0x0060: 0x002d, # HYPHEN-MINUS 0x0061: 0x002f, # SOLIDUS 0x0062: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x0063: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0064: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x0065: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x0066: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x0067: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0068: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0069: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x006a: 0x00a6, # BROKEN BAR 0x006b: 0x002c, # COMMA 0x006c: 0x0025, # PERCENT SIGN 0x006d: 0x005f, # LOW LINE 0x006e: 0x003e, # GREATER-THAN SIGN 0x006f: 0x003f, # QUESTION MARK 0x0070: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x0071: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0072: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x0073: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x0074: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x0075: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x0076: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x0077: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x0078: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x0079: 0x0060, # GRAVE ACCENT 0x007a: 0x003a, # COLON 0x007b: 0x0023, # NUMBER SIGN 0x007c: 0x0040, # COMMERCIAL AT 0x007d: 0x0027, # APOSTROPHE 0x007e: 0x003d, # EQUALS SIGN 0x007f: 0x0022, # QUOTATION MARK 0x0080: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x0081: 0x0061, # LATIN SMALL LETTER A 0x0082: 0x0062, # LATIN SMALL LETTER B 0x0083: 0x0063, # LATIN SMALL LETTER C 0x0084: 0x0064, # LATIN SMALL LETTER D 0x0085: 0x0065, # LATIN SMALL LETTER E 0x0086: 0x0066, # LATIN SMALL LETTER F 0x0087: 0x0067, # LATIN SMALL LETTER G 0x0088: 0x0068, # LATIN SMALL LETTER H 0x0089: 0x0069, # LATIN SMALL LETTER I 0x008a: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008b: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x008c: 0x00f0, # LATIN SMALL LETTER ETH (ICELANDIC) 0x008d: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x008e: 0x00fe, # LATIN SMALL LETTER THORN (ICELANDIC) 0x008f: 0x00b1, # PLUS-MINUS SIGN 0x0090: 0x00b0, # DEGREE SIGN 0x0091: 0x006a, # LATIN SMALL LETTER J 0x0092: 0x006b, # LATIN SMALL LETTER K 0x0093: 0x006c, # LATIN SMALL LETTER L 0x0094: 0x006d, # LATIN SMALL LETTER M 0x0095: 0x006e, # LATIN SMALL LETTER N 0x0096: 0x006f, # LATIN SMALL LETTER O 0x0097: 0x0070, # LATIN SMALL LETTER P 0x0098: 0x0071, # LATIN SMALL LETTER Q 0x0099: 0x0072, # LATIN SMALL LETTER R 0x009a: 0x00aa, # FEMININE ORDINAL INDICATOR 0x009b: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x009c: 0x00e6, # LATIN SMALL LIGATURE AE 0x009d: 0x00b8, # CEDILLA 0x009e: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x009f: 0x00a4, # CURRENCY SIGN 0x00a0: 0x00b5, # MICRO SIGN 0x00a1: 0x007e, # TILDE 0x00a2: 0x0073, # LATIN SMALL LETTER S 0x00a3: 0x0074, # LATIN SMALL LETTER T 0x00a4: 0x0075, # LATIN SMALL LETTER U 0x00a5: 0x0076, # LATIN SMALL LETTER V 0x00a6: 0x0077, # LATIN SMALL LETTER W 0x00a7: 0x0078, # LATIN SMALL LETTER X 0x00a8: 0x0079, # LATIN SMALL LETTER Y 0x00a9: 0x007a, # LATIN SMALL LETTER Z 0x00aa: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ab: 0x00bf, # INVERTED QUESTION MARK 0x00ac: 0x00d0, # LATIN CAPITAL LETTER ETH (ICELANDIC) 0x00ad: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ae: 0x00de, # LATIN CAPITAL LETTER THORN (ICELANDIC) 0x00af: 0x00ae, # REGISTERED SIGN 0x00b0: 0x00a2, # CENT SIGN 0x00b1: 0x00a3, # POUND SIGN 0x00b2: 0x00a5, # YEN SIGN 0x00b3: 0x00b7, # MIDDLE DOT 0x00b4: 0x00a9, # COPYRIGHT SIGN 0x00b5: 0x00a7, # SECTION SIGN 0x00b7: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00b8: 0x00bd, # VULGAR FRACTION ONE HALF 0x00b9: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00ba: 0x00ac, # NOT SIGN 0x00bb: 0x007c, # VERTICAL LINE 0x00bc: 0x00af, # MACRON 0x00bd: 0x00a8, # DIAERESIS 0x00be: 0x00b4, # ACUTE ACCENT 0x00bf: 0x00d7, # MULTIPLICATION SIGN 0x00c0: 0x007b, # LEFT CURLY BRACKET 0x00c1: 0x0041, # LATIN CAPITAL LETTER A 0x00c2: 0x0042, # LATIN CAPITAL LETTER B 0x00c3: 0x0043, # LATIN CAPITAL LETTER C 0x00c4: 0x0044, # LATIN CAPITAL LETTER D 0x00c5: 0x0045, # LATIN CAPITAL LETTER E 0x00c6: 0x0046, # LATIN CAPITAL LETTER F 0x00c7: 0x0047, # LATIN CAPITAL LETTER G 0x00c8: 0x0048, # LATIN CAPITAL LETTER H 0x00c9: 0x0049, # LATIN CAPITAL LETTER I 0x00ca: 0x00ad, # SOFT HYPHEN 0x00cb: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00cc: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x00cd: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x00ce: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00cf: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00d0: 0x007d, # RIGHT CURLY BRACKET 0x00d1: 0x004a, # LATIN CAPITAL LETTER J 0x00d2: 0x004b, # LATIN CAPITAL LETTER K 0x00d3: 0x004c, # LATIN CAPITAL LETTER L 0x00d4: 0x004d, # LATIN CAPITAL LETTER M 0x00d5: 0x004e, # LATIN CAPITAL LETTER N 0x00d6: 0x004f, # LATIN CAPITAL LETTER O 0x00d7: 0x0050, # LATIN CAPITAL LETTER P 0x00d8: 0x0051, # LATIN CAPITAL LETTER Q 0x00d9: 0x0052, # LATIN CAPITAL LETTER R 0x00da: 0x00b9, # SUPERSCRIPT ONE 0x00db: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00dc: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00dd: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x00de: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00df: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00e0: 0x005c, # REVERSE SOLIDUS 0x00e1: 0x00f7, # DIVISION SIGN 0x00e2: 0x0053, # LATIN CAPITAL LETTER S 0x00e3: 0x0054, # LATIN CAPITAL LETTER T 0x00e4: 0x0055, # LATIN CAPITAL LETTER U 0x00e5: 0x0056, # LATIN CAPITAL LETTER V 0x00e6: 0x0057, # LATIN CAPITAL LETTER W 0x00e7: 0x0058, # LATIN CAPITAL LETTER X 0x00e8: 0x0059, # LATIN CAPITAL LETTER Y 0x00e9: 0x005a, # LATIN CAPITAL LETTER Z 0x00ea: 0x00b2, # SUPERSCRIPT TWO 0x00eb: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00ec: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00ed: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00f0: 0x0030, # DIGIT ZERO 0x00f1: 0x0031, # DIGIT ONE 0x00f2: 0x0032, # DIGIT TWO 0x00f3: 0x0033, # DIGIT THREE 0x00f4: 0x0034, # DIGIT FOUR 0x00f5: 0x0035, # DIGIT FIVE 0x00f6: 0x0036, # DIGIT SIX 0x00f7: 0x0037, # DIGIT SEVEN 0x00f8: 0x0038, # DIGIT EIGHT 0x00f9: 0x0039, # DIGIT NINE 0x00fa: 0x00b3, # SUPERSCRIPT THREE 0x00fb: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00fc: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00fd: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00fe: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ff: 0x009f, # CONTROL }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
Python
# # iso2022_jp_3.py: Python Unicode Codec for ISO2022_JP_3 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # $CJKCodecs: iso2022_jp_3.py,v 1.2 2004/06/28 18:16:03 perky Exp $ # import _codecs_iso2022, codecs codec = _codecs_iso2022.getcodec('iso2022_jp_3') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class StreamReader(Codec, codecs.StreamReader): def __init__(self, stream, errors='strict'): codecs.StreamReader.__init__(self, stream, errors) __codec = codec.StreamReader(stream, errors) self.read = __codec.read self.readline = __codec.readline self.readlines = __codec.readlines self.reset = __codec.reset class StreamWriter(Codec, codecs.StreamWriter): def __init__(self, stream, errors='strict'): codecs.StreamWriter.__init__(self, stream, errors) __codec = codec.StreamWriter(stream, errors) self.write = __codec.write self.writelines = __codec.writelines self.reset = __codec.reset def getregentry(): return (codec.encode, codec.decode, StreamReader, StreamWriter)
Python
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support module for sre""" # update when constants are added or removed MAGIC = 20031017 # max code word in this release MAXREPEAT = 65535 # SRE standard exception (access as sre.error) # should this really be here? class error(Exception): pass # operators FAILURE = "failure" SUCCESS = "success" ANY = "any" ANY_ALL = "any_all" ASSERT = "assert" ASSERT_NOT = "assert_not" AT = "at" BIGCHARSET = "bigcharset" BRANCH = "branch" CALL = "call" CATEGORY = "category" CHARSET = "charset" GROUPREF = "groupref" GROUPREF_IGNORE = "groupref_ignore" GROUPREF_EXISTS = "groupref_exists" IN = "in" IN_IGNORE = "in_ignore" INFO = "info" JUMP = "jump" LITERAL = "literal" LITERAL_IGNORE = "literal_ignore" MARK = "mark" MAX_REPEAT = "max_repeat" MAX_UNTIL = "max_until" MIN_REPEAT = "min_repeat" MIN_UNTIL = "min_until" NEGATE = "negate" NOT_LITERAL = "not_literal" NOT_LITERAL_IGNORE = "not_literal_ignore" RANGE = "range" REPEAT = "repeat" REPEAT_ONE = "repeat_one" SUBPATTERN = "subpattern" MIN_REPEAT_ONE = "min_repeat_one" # positions AT_BEGINNING = "at_beginning" AT_BEGINNING_LINE = "at_beginning_line" AT_BEGINNING_STRING = "at_beginning_string" AT_BOUNDARY = "at_boundary" AT_NON_BOUNDARY = "at_non_boundary" AT_END = "at_end" AT_END_LINE = "at_end_line" AT_END_STRING = "at_end_string" AT_LOC_BOUNDARY = "at_loc_boundary" AT_LOC_NON_BOUNDARY = "at_loc_non_boundary" AT_UNI_BOUNDARY = "at_uni_boundary" AT_UNI_NON_BOUNDARY = "at_uni_non_boundary" # categories CATEGORY_DIGIT = "category_digit" CATEGORY_NOT_DIGIT = "category_not_digit" CATEGORY_SPACE = "category_space" CATEGORY_NOT_SPACE = "category_not_space" CATEGORY_WORD = "category_word" CATEGORY_NOT_WORD = "category_not_word" CATEGORY_LINEBREAK = "category_linebreak" CATEGORY_NOT_LINEBREAK = "category_not_linebreak" CATEGORY_LOC_WORD = "category_loc_word" CATEGORY_LOC_NOT_WORD = "category_loc_not_word" CATEGORY_UNI_DIGIT = "category_uni_digit" CATEGORY_UNI_NOT_DIGIT = "category_uni_not_digit" CATEGORY_UNI_SPACE = "category_uni_space" CATEGORY_UNI_NOT_SPACE = "category_uni_not_space" CATEGORY_UNI_WORD = "category_uni_word" CATEGORY_UNI_NOT_WORD = "category_uni_not_word" CATEGORY_UNI_LINEBREAK = "category_uni_linebreak" CATEGORY_UNI_NOT_LINEBREAK = "category_uni_not_linebreak" OPCODES = [ # failure=0 success=1 (just because it looks better that way :-) FAILURE, SUCCESS, ANY, ANY_ALL, ASSERT, ASSERT_NOT, AT, BRANCH, CALL, CATEGORY, CHARSET, BIGCHARSET, GROUPREF, GROUPREF_EXISTS, GROUPREF_IGNORE, IN, IN_IGNORE, INFO, JUMP, LITERAL, LITERAL_IGNORE, MARK, MAX_UNTIL, MIN_UNTIL, NOT_LITERAL, NOT_LITERAL_IGNORE, NEGATE, RANGE, REPEAT, REPEAT_ONE, SUBPATTERN, MIN_REPEAT_ONE ] # PyPy hack to make the sre_*.py files from 2.4.1 work on the _sre # engine of 2.3. import _sre if _sre.MAGIC < 20031017: OPCODES.remove(GROUPREF_EXISTS) del _sre ATCODES = [ AT_BEGINNING, AT_BEGINNING_LINE, AT_BEGINNING_STRING, AT_BOUNDARY, AT_NON_BOUNDARY, AT_END, AT_END_LINE, AT_END_STRING, AT_LOC_BOUNDARY, AT_LOC_NON_BOUNDARY, AT_UNI_BOUNDARY, AT_UNI_NON_BOUNDARY ] CHCODES = [ CATEGORY_DIGIT, CATEGORY_NOT_DIGIT, CATEGORY_SPACE, CATEGORY_NOT_SPACE, CATEGORY_WORD, CATEGORY_NOT_WORD, CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK, CATEGORY_LOC_WORD, CATEGORY_LOC_NOT_WORD, CATEGORY_UNI_DIGIT, CATEGORY_UNI_NOT_DIGIT, CATEGORY_UNI_SPACE, CATEGORY_UNI_NOT_SPACE, CATEGORY_UNI_WORD, CATEGORY_UNI_NOT_WORD, CATEGORY_UNI_LINEBREAK, CATEGORY_UNI_NOT_LINEBREAK ] def makedict(list): d = {} i = 0 for item in list: d[item] = i i = i + 1 return d OPCODES = makedict(OPCODES) ATCODES = makedict(ATCODES) CHCODES = makedict(CHCODES) # replacement operations for "ignore case" mode OP_IGNORE = { GROUPREF: GROUPREF_IGNORE, IN: IN_IGNORE, LITERAL: LITERAL_IGNORE, NOT_LITERAL: NOT_LITERAL_IGNORE } AT_MULTILINE = { AT_BEGINNING: AT_BEGINNING_LINE, AT_END: AT_END_LINE } AT_LOCALE = { AT_BOUNDARY: AT_LOC_BOUNDARY, AT_NON_BOUNDARY: AT_LOC_NON_BOUNDARY } AT_UNICODE = { AT_BOUNDARY: AT_UNI_BOUNDARY, AT_NON_BOUNDARY: AT_UNI_NON_BOUNDARY } CH_LOCALE = { CATEGORY_DIGIT: CATEGORY_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_SPACE, CATEGORY_NOT_SPACE: CATEGORY_NOT_SPACE, CATEGORY_WORD: CATEGORY_LOC_WORD, CATEGORY_NOT_WORD: CATEGORY_LOC_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_NOT_LINEBREAK } CH_UNICODE = { CATEGORY_DIGIT: CATEGORY_UNI_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_UNI_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_UNI_SPACE, CATEGORY_NOT_SPACE: CATEGORY_UNI_NOT_SPACE, CATEGORY_WORD: CATEGORY_UNI_WORD, CATEGORY_NOT_WORD: CATEGORY_UNI_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_UNI_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_UNI_NOT_LINEBREAK } # flags SRE_FLAG_TEMPLATE = 1 # template mode (disable backtracking) SRE_FLAG_IGNORECASE = 2 # case insensitive SRE_FLAG_LOCALE = 4 # honour system locale SRE_FLAG_MULTILINE = 8 # treat target as multiline string SRE_FLAG_DOTALL = 16 # treat target as a single string SRE_FLAG_UNICODE = 32 # use unicode locale SRE_FLAG_VERBOSE = 64 # ignore whitespace and comments SRE_FLAG_DEBUG = 128 # debugging # flags for INFO primitive SRE_INFO_PREFIX = 1 # has prefix SRE_INFO_LITERAL = 2 # entire pattern is literal (given by prefix) SRE_INFO_CHARSET = 4 # pattern starts with character from given set if __name__ == "__main__": def dump(f, d, prefix): items = d.items() items.sort(key=lambda a: a[1]) for k, v in items: f.write("#define %s_%s %s\n" % (prefix, k.upper(), v)) f = open("sre_constants.h", "w") f.write("""\ /* * Secret Labs' Regular Expression Engine * * regular expression matching engine * * NOTE: This file is generated by sre_constants.py. If you need * to change anything in here, edit sre_constants.py and run it. * * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. * * See the _sre.c file for information on usage and redistribution. */ """) f.write("#define SRE_MAGIC %d\n" % MAGIC) dump(f, OPCODES, "SRE_OP") dump(f, ATCODES, "SRE") dump(f, CHCODES, "SRE") f.write("#define SRE_FLAG_TEMPLATE %d\n" % SRE_FLAG_TEMPLATE) f.write("#define SRE_FLAG_IGNORECASE %d\n" % SRE_FLAG_IGNORECASE) f.write("#define SRE_FLAG_LOCALE %d\n" % SRE_FLAG_LOCALE) f.write("#define SRE_FLAG_MULTILINE %d\n" % SRE_FLAG_MULTILINE) f.write("#define SRE_FLAG_DOTALL %d\n" % SRE_FLAG_DOTALL) f.write("#define SRE_FLAG_UNICODE %d\n" % SRE_FLAG_UNICODE) f.write("#define SRE_FLAG_VERBOSE %d\n" % SRE_FLAG_VERBOSE) f.write("#define SRE_INFO_PREFIX %d\n" % SRE_INFO_PREFIX) f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL) f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) f.close() print "done"
Python
"""Generic (shallow and deep) copying operations. Interface summary: import copy x = copy.copy(y) # make a shallow copy of y x = copy.deepcopy(y) # make a deep copy of y For module specific errors, copy.Error is raised. The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances). - A shallow copy constructs a new compound object and then (to the extent possible) inserts *the same objects* into in that the original contains. - A deep copy constructs a new compound object and then, recursively, inserts *copies* into it of the objects found in the original. Two problems often exist with deep copy operations that don't exist with shallow copy operations: a) recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop b) because deep copy copies *everything* it may copy too much, e.g. administrative data structures that should be shared even between copies Python's deep copy operation avoids these problems by: a) keeping a table of objects already copied during the current copying pass b) letting user-defined classes override the copying operation or the set of components copied This version does not copy types like module, class, function, method, nor stack trace, stack frame, nor file, socket, window, nor array, nor any similar types. Classes can use the same interfaces to control copying that they use to control pickling: they can define methods called __getinitargs__(), __getstate__() and __setstate__(). See the documentation for module "pickle" for information on these methods. """ import types from copy_reg import dispatch_table class Error(Exception): pass error = Error # backward compatibility try: from org.python.core import PyStringMap except ImportError: PyStringMap = None __all__ = ["Error", "copy", "deepcopy"] def _getspecial(cls, name): def getmro(cls): def _searchbases(cls): # Simulate the "classic class" search order. if cls in result: return result.append(cls) for base in cls.__bases__: _searchbases(base) if hasattr(cls, "__mro__"): return cls.__mro__ else: result = [] _searchbases(cls) return result for basecls in getmro(cls): try: return basecls.__dict__[name] except: pass else: return None def copy(x): """Shallow copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ cls = type(x) copier = _copy_dispatch.get(cls) if copier: return copier(x) copier = _getspecial(cls, "__copy__") if copier: return copier(x) reductor = dispatch_table.get(cls) if reductor: rv = reductor(x) else: reductor = getattr(x, "__reduce_ex__", None) if reductor: rv = reductor(2) else: reductor = getattr(x, "__reduce__", None) if reductor: rv = reductor() else: copier = getattr(x, "__copy__", None) if copier: return copier() raise Error("un(shallow)copyable object of type %s" % cls) return _reconstruct(x, rv, 0) _copy_dispatch = d = {} def _copy_immutable(x): return x for t in (types.NoneType, int, long, float, bool, str, tuple, frozenset, type, xrange, types.ClassType, types.BuiltinFunctionType): d[t] = _copy_immutable for name in ("ComplexType", "UnicodeType", "CodeType"): t = getattr(types, name, None) if t is not None: d[t] = _copy_immutable def _copy_with_constructor(x): return type(x)(x) for t in (list, dict, set): d[t] = _copy_with_constructor def _copy_with_copy_method(x): return x.copy() if PyStringMap is not None: d[PyStringMap] = _copy_with_copy_method def _copy_inst(x): if hasattr(x, '__copy__'): return x.__copy__() if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() y = x.__class__(*args) else: y = _EmptyClass() y.__class__ = x.__class__ if hasattr(x, '__getstate__'): state = x.__getstate__() else: state = x.__dict__ if hasattr(y, '__setstate__'): y.__setstate__(state) else: y.__dict__.update(state) return y d[types.InstanceType] = _copy_inst del d def deepcopy(x, memo=None, _nil=[]): """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ if memo is None: memo = {} d = id(x) y = memo.get(d, _nil) if y is not _nil: return y cls = type(x) copier = _deepcopy_dispatch.get(cls) if copier: y = copier(x, memo) else: try: issc = issubclass(cls, type) except TypeError: # cls is not a class (old Boost; see SF #502085) issc = 0 if issc: y = _deepcopy_atomic(x, memo) else: copier = _getspecial(cls, "__deepcopy__") if copier: y = copier(x, memo) else: reductor = dispatch_table.get(cls) if reductor: rv = reductor(x) else: reductor = getattr(x, "__reduce_ex__", None) if reductor: rv = reductor(2) else: reductor = getattr(x, "__reduce__", None) if reductor: rv = reductor() else: copier = getattr(x, "__deepcopy__", None) if copier: return copier(memo) raise Error( "un(deep)copyable object of type %s" % cls) y = _reconstruct(x, rv, 1, memo) memo[d] = y _keep_alive(x, memo) # Make sure x lives at least as long as d return y _deepcopy_dispatch = d = {} def _deepcopy_atomic(x, memo): return x d[types.NoneType] = _deepcopy_atomic d[types.IntType] = _deepcopy_atomic d[types.LongType] = _deepcopy_atomic d[types.FloatType] = _deepcopy_atomic d[types.BooleanType] = _deepcopy_atomic try: d[types.ComplexType] = _deepcopy_atomic except AttributeError: pass d[types.StringType] = _deepcopy_atomic try: d[types.UnicodeType] = _deepcopy_atomic except AttributeError: pass try: d[types.CodeType] = _deepcopy_atomic except AttributeError: pass d[types.TypeType] = _deepcopy_atomic d[types.XRangeType] = _deepcopy_atomic d[types.ClassType] = _deepcopy_atomic d[types.BuiltinFunctionType] = _deepcopy_atomic def _deepcopy_list(x, memo): y = [] memo[id(x)] = y for a in x: y.append(deepcopy(a, memo)) return y d[types.ListType] = _deepcopy_list def _deepcopy_tuple(x, memo): y = [] for a in x: y.append(deepcopy(a, memo)) d = id(x) try: return memo[d] except KeyError: pass for i in range(len(x)): if x[i] is not y[i]: y = tuple(y) break else: y = x memo[d] = y return y d[types.TupleType] = _deepcopy_tuple def _deepcopy_dict(x, memo): y = {} memo[id(x)] = y for key, value in x.iteritems(): y[deepcopy(key, memo)] = deepcopy(value, memo) return y d[types.DictionaryType] = _deepcopy_dict if PyStringMap is not None: d[PyStringMap] = _deepcopy_dict def _keep_alive(x, memo): """Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo itself... """ try: memo[id(memo)].append(x) except KeyError: # aha, this is the first one :-) memo[id(memo)]=[x] def _deepcopy_inst(x, memo): if hasattr(x, '__deepcopy__'): return x.__deepcopy__(memo) if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() args = deepcopy(args, memo) y = x.__class__(*args) else: y = _EmptyClass() y.__class__ = x.__class__ memo[id(x)] = y if hasattr(x, '__getstate__'): state = x.__getstate__() else: state = x.__dict__ state = deepcopy(state, memo) if hasattr(y, '__setstate__'): y.__setstate__(state) else: y.__dict__.update(state) return y d[types.InstanceType] = _deepcopy_inst def _reconstruct(x, info, deep, memo=None): if isinstance(info, str): return x assert isinstance(info, tuple) if memo is None: memo = {} n = len(info) assert n in (2, 3, 4, 5) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if n > 3: listiter = info[3] else: listiter = None if n > 4: dictiter = info[4] else: dictiter = None if deep: args = deepcopy(args, memo) y = callable(*args) memo[id(x)] = y if listiter is not None: for item in listiter: if deep: item = deepcopy(item, memo) y.append(item) if dictiter is not None: for key, value in dictiter: if deep: key = deepcopy(key, memo) value = deepcopy(value, memo) y[key] = value if state: if deep: state = deepcopy(state, memo) if hasattr(y, '__setstate__'): y.__setstate__(state) else: if isinstance(state, tuple) and len(state) == 2: state, slotstate = state else: slotstate = None if state is not None: y.__dict__.update(state) if slotstate is not None: for key, value in slotstate.iteritems(): setattr(y, key, value) return y del d del types # Helper for instance creation without calling __init__ class _EmptyClass: pass def _test(): l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'], {'abc': 'ABC'}, (), [], {}] l1 = copy(l) print l1==l l1 = map(copy, l) print l1==l l1 = deepcopy(l) print l1==l class C: def __init__(self, arg=None): self.a = 1 self.arg = arg if __name__ == '__main__': import sys file = sys.argv[0] else: file = __file__ self.fp = open(file) self.fp.close() def __getstate__(self): return {'a': self.a, 'arg': self.arg} def __setstate__(self, state): for key, value in state.iteritems(): setattr(self, key, value) def __deepcopy__(self, memo=None): new = self.__class__(deepcopy(self.arg, memo)) new.a = self.a return new c = C('argument sketch') l.append(c) l2 = copy(l) print l == l2 print l print l2 l2 = deepcopy(l) print l == l2 print l print l2 l.append({l[1]: l, 'xyz': l[2]}) l3 = copy(l) import repr print map(repr.repr, l) print map(repr.repr, l1) print map(repr.repr, l2) print map(repr.repr, l3) l3 = deepcopy(l) import repr print map(repr.repr, l) print map(repr.repr, l1) print map(repr.repr, l2) print map(repr.repr, l3) if __name__ == '__main__': _test()
Python
'''"Executable documentation" for the pickle module. Extensive comments about the pickle protocols and pickle-machine opcodes can be found here. Some functions meant for external use: genops(pickle) Generate all the opcodes in a pickle, as (opcode, arg, position) triples. dis(pickle, out=None, memo=None, indentlevel=4) Print a symbolic disassembly of a pickle. ''' __all__ = ['dis', 'genops', ] # Other ideas: # # - A pickle verifier: read a pickle and check it exhaustively for # well-formedness. dis() does a lot of this already. # # - A protocol identifier: examine a pickle and return its protocol number # (== the highest .proto attr value among all the opcodes in the pickle). # dis() already prints this info at the end. # # - A pickle optimizer: for example, tuple-building code is sometimes more # elaborate than necessary, catering for the possibility that the tuple # is recursive. Or lots of times a PUT is generated that's never accessed # by a later GET. """ "A pickle" is a program for a virtual pickle machine (PM, but more accurately called an unpickling machine). It's a sequence of opcodes, interpreted by the PM, building an arbitrarily complex Python object. For the most part, the PM is very simple: there are no looping, testing, or conditional instructions, no arithmetic and no function calls. Opcodes are executed once each, from first to last, until a STOP opcode is reached. The PM has two data areas, "the stack" and "the memo". Many opcodes push Python objects onto the stack; e.g., INT pushes a Python integer object on the stack, whose value is gotten from a decimal string literal immediately following the INT opcode in the pickle bytestream. Other opcodes take Python objects off the stack. The result of unpickling is whatever object is left on the stack when the final STOP opcode is executed. The memo is simply an array of objects, or it can be implemented as a dict mapping little integers to objects. The memo serves as the PM's "long term memory", and the little integers indexing the memo are akin to variable names. Some opcodes pop a stack object into the memo at a given index, and others push a memo object at a given index onto the stack again. At heart, that's all the PM has. Subtleties arise for these reasons: + Object identity. Objects can be arbitrarily complex, and subobjects may be shared (for example, the list [a, a] refers to the same object a twice). It can be vital that unpickling recreate an isomorphic object graph, faithfully reproducing sharing. + Recursive objects. For example, after "L = []; L.append(L)", L is a list, and L[0] is the same list. This is related to the object identity point, and some sequences of pickle opcodes are subtle in order to get the right result in all cases. + Things pickle doesn't know everything about. Examples of things pickle does know everything about are Python's builtin scalar and container types, like ints and tuples. They generally have opcodes dedicated to them. For things like module references and instances of user-defined classes, pickle's knowledge is limited. Historically, many enhancements have been made to the pickle protocol in order to do a better (faster, and/or more compact) job on those. + Backward compatibility and micro-optimization. As explained below, pickle opcodes never go away, not even when better ways to do a thing get invented. The repertoire of the PM just keeps growing over time. For example, protocol 0 had two opcodes for building Python integers (INT and LONG), protocol 1 added three more for more-efficient pickling of short integers, and protocol 2 added two more for more-efficient pickling of long integers (before protocol 2, the only ways to pickle a Python long took time quadratic in the number of digits, for both pickling and unpickling). "Opcode bloat" isn't so much a subtlety as a source of wearying complication. Pickle protocols: For compatibility, the meaning of a pickle opcode never changes. Instead new pickle opcodes get added, and each version's unpickler can handle all the pickle opcodes in all protocol versions to date. So old pickles continue to be readable forever. The pickler can generally be told to restrict itself to the subset of opcodes available under previous protocol versions too, so that users can create pickles under the current version readable by older versions. However, a pickle does not contain its version number embedded within it. If an older unpickler tries to read a pickle using a later protocol, the result is most likely an exception due to seeing an unknown (in the older unpickler) opcode. The original pickle used what's now called "protocol 0", and what was called "text mode" before Python 2.3. The entire pickle bytestream is made up of printable 7-bit ASCII characters, plus the newline character, in protocol 0. That's why it was called text mode. Protocol 0 is small and elegant, but sometimes painfully inefficient. The second major set of additions is now called "protocol 1", and was called "binary mode" before Python 2.3. This added many opcodes with arguments consisting of arbitrary bytes, including NUL bytes and unprintable "high bit" bytes. Binary mode pickles can be substantially smaller than equivalent text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte int as 4 bytes following the opcode, which is cheaper to unpickle than the (perhaps) 11-character decimal string attached to INT. Protocol 1 also added a number of opcodes that operate on many stack elements at once (like APPENDS and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE). The third major set of additions came in Python 2.3, and is called "protocol 2". This added: - A better way to pickle instances of new-style classes (NEWOBJ). - A way for a pickle to identify its protocol (PROTO). - Time- and space- efficient pickling of long ints (LONG{1,4}). - Shortcuts for small tuples (TUPLE{1,2,3}}. - Dedicated opcodes for bools (NEWTRUE, NEWFALSE). - The "extension registry", a vector of popular objects that can be pushed efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but the registry contents are predefined (there's nothing akin to the memo's PUT). Another independent change with Python 2.3 is the abandonment of any pretense that it might be safe to load pickles received from untrusted parties -- no sufficient security analysis has been done to guarantee this and there isn't a use case that warrants the expense of such an analysis. To this end, all tests for __safe_for_unpickling__ or for copy_reg.safe_constructors are removed from the unpickling code. References to these variables in the descriptions below are to be seen as describing unpickling in Python 2.2 and before. """ # Meta-rule: Descriptions are stored in instances of descriptor objects, # with plain constructors. No meta-language is defined from which # descriptors could be constructed. If you want, e.g., XML, write a little # program to generate XML from the objects. ############################################################################## # Some pickle opcodes have an argument, following the opcode in the # bytestream. An argument is of a specific type, described by an instance # of ArgumentDescriptor. These are not to be confused with arguments taken # off the stack -- ArgumentDescriptor applies only to arguments embedded in # the opcode stream, immediately following an opcode. # Represents the number of bytes consumed by an argument delimited by the # next newline character. UP_TO_NEWLINE = -1 # Represents the number of bytes consumed by a two-argument opcode where # the first argument gives the number of bytes in the second argument. TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int class ArgumentDescriptor(object): __slots__ = ( # name of descriptor record, also a module global name; a string 'name', # length of argument, in bytes; an int; UP_TO_NEWLINE and # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length # cases 'n', # a function taking a file-like object, reading this kind of argument # from the object at the current position, advancing the current # position by n bytes, and returning the value of the argument 'reader', # human-readable docs for this arg descriptor; a string 'doc', ) def __init__(self, name, n, reader, doc): assert isinstance(name, str) self.name = name assert isinstance(n, int) and (n >= 0 or n in (UP_TO_NEWLINE, TAKEN_FROM_ARGUMENT1, TAKEN_FROM_ARGUMENT4)) self.n = n self.reader = reader assert isinstance(doc, str) self.doc = doc from struct import unpack as _unpack def read_uint1(f): r""" >>> import StringIO >>> read_uint1(StringIO.StringIO('\xff')) 255 """ data = f.read(1) if data: return ord(data) raise ValueError("not enough data in stream to read uint1") uint1 = ArgumentDescriptor( name='uint1', n=1, reader=read_uint1, doc="One-byte unsigned integer.") def read_uint2(f): r""" >>> import StringIO >>> read_uint2(StringIO.StringIO('\xff\x00')) 255 >>> read_uint2(StringIO.StringIO('\xff\xff')) 65535 """ data = f.read(2) if len(data) == 2: return _unpack("<H", data)[0] raise ValueError("not enough data in stream to read uint2") uint2 = ArgumentDescriptor( name='uint2', n=2, reader=read_uint2, doc="Two-byte unsigned integer, little-endian.") def read_int4(f): r""" >>> import StringIO >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00')) 255 >>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31) True """ data = f.read(4) if len(data) == 4: return _unpack("<i", data)[0] raise ValueError("not enough data in stream to read int4") int4 = ArgumentDescriptor( name='int4', n=4, reader=read_int4, doc="Four-byte signed integer, little-endian, 2's complement.") def read_stringnl(f, decode=True, stripquotes=True): r""" >>> import StringIO >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n")) 'abcd' >>> read_stringnl(StringIO.StringIO("\n")) Traceback (most recent call last): ... ValueError: no string quotes around '' >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False) '' >>> read_stringnl(StringIO.StringIO("''\n")) '' >>> read_stringnl(StringIO.StringIO('"abcd"')) Traceback (most recent call last): ... ValueError: no newline found when trying to read stringnl Embedded escapes are undone in the result. >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'")) 'a\n\\b\x00c\td' """ data = f.readline() if not data.endswith('\n'): raise ValueError("no newline found when trying to read stringnl") data = data[:-1] # lose the newline if stripquotes: for q in "'\"": if data.startswith(q): if not data.endswith(q): raise ValueError("strinq quote %r not found at both " "ends of %r" % (q, data)) data = data[1:-1] break else: raise ValueError("no string quotes around %r" % data) # I'm not sure when 'string_escape' was added to the std codecs; it's # crazy not to use it if it's there. if decode: data = data.decode('string_escape') return data stringnl = ArgumentDescriptor( name='stringnl', n=UP_TO_NEWLINE, reader=read_stringnl, doc="""A newline-terminated string. This is a repr-style string, with embedded escapes, and bracketing quotes. """) def read_stringnl_noescape(f): return read_stringnl(f, decode=False, stripquotes=False) stringnl_noescape = ArgumentDescriptor( name='stringnl_noescape', n=UP_TO_NEWLINE, reader=read_stringnl_noescape, doc="""A newline-terminated string. This is a str-style string, without embedded escapes, or bracketing quotes. It should consist solely of printable ASCII characters. """) def read_stringnl_noescape_pair(f): r""" >>> import StringIO >>> read_stringnl_noescape_pair(StringIO.StringIO("Queue\nEmpty\njunk")) 'Queue Empty' """ return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f)) stringnl_noescape_pair = ArgumentDescriptor( name='stringnl_noescape_pair', n=UP_TO_NEWLINE, reader=read_stringnl_noescape_pair, doc="""A pair of newline-terminated strings. These are str-style strings, without embedded escapes, or bracketing quotes. They should consist solely of printable ASCII characters. The pair is returned as a single string, with a single blank separating the two strings. """) def read_string4(f): r""" >>> import StringIO >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc")) '' >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef")) 'abc' >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef")) Traceback (most recent call last): ... ValueError: expected 50331648 bytes in a string4, but only 6 remain """ n = read_int4(f) if n < 0: raise ValueError("string4 byte count < 0: %d" % n) data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a string4, but only %d remain" % (n, len(data))) string4 = ArgumentDescriptor( name="string4", n=TAKEN_FROM_ARGUMENT4, reader=read_string4, doc="""A counted string. The first argument is a 4-byte little-endian signed int giving the number of bytes in the string, and the second argument is that many bytes. """) def read_string1(f): r""" >>> import StringIO >>> read_string1(StringIO.StringIO("\x00")) '' >>> read_string1(StringIO.StringIO("\x03abcdef")) 'abc' """ n = read_uint1(f) assert n >= 0 data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a string1, but only %d remain" % (n, len(data))) string1 = ArgumentDescriptor( name="string1", n=TAKEN_FROM_ARGUMENT1, reader=read_string1, doc="""A counted string. The first argument is a 1-byte unsigned int giving the number of bytes in the string, and the second argument is that many bytes. """) def read_unicodestringnl(f): r""" >>> import StringIO >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk")) u'abc\uabcd' """ data = f.readline() if not data.endswith('\n'): raise ValueError("no newline found when trying to read " "unicodestringnl") data = data[:-1] # lose the newline return unicode(data, 'raw-unicode-escape') unicodestringnl = ArgumentDescriptor( name='unicodestringnl', n=UP_TO_NEWLINE, reader=read_unicodestringnl, doc="""A newline-terminated Unicode string. This is raw-unicode-escape encoded, so consists of printable ASCII characters, and may contain embedded escape sequences. """) def read_unicodestring4(f): r""" >>> import StringIO >>> s = u'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc 'abcd\xea\xaf\x8d' >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk')) >>> s == t True >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring4, but only 6 remain """ n = read_int4(f) if n < 0: raise ValueError("unicodestring4 byte count < 0: %d" % n) data = f.read(n) if len(data) == n: return unicode(data, 'utf-8') raise ValueError("expected %d bytes in a unicodestring4, but only %d " "remain" % (n, len(data))) unicodestring4 = ArgumentDescriptor( name="unicodestring4", n=TAKEN_FROM_ARGUMENT4, reader=read_unicodestring4, doc="""A counted Unicode string. The first argument is a 4-byte little-endian signed int giving the number of bytes in the string, and the second argument-- the UTF-8 encoding of the Unicode string -- contains that many bytes. """) def read_decimalnl_short(f): r""" >>> import StringIO >>> read_decimalnl_short(StringIO.StringIO("1234\n56")) 1234 >>> read_decimalnl_short(StringIO.StringIO("1234L\n56")) Traceback (most recent call last): ... ValueError: trailing 'L' not allowed in '1234L' """ s = read_stringnl(f, decode=False, stripquotes=False) if s.endswith("L"): raise ValueError("trailing 'L' not allowed in %r" % s) # It's not necessarily true that the result fits in a Python short int: # the pickle may have been written on a 64-bit box. There's also a hack # for True and False here. if s == "00": return False elif s == "01": return True try: return int(s) except OverflowError: return long(s) def read_decimalnl_long(f): r""" >>> import StringIO >>> read_decimalnl_long(StringIO.StringIO("1234\n56")) Traceback (most recent call last): ... ValueError: trailing 'L' required in '1234' Someday the trailing 'L' will probably go away from this output. >>> read_decimalnl_long(StringIO.StringIO("1234L\n56")) 1234L >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6")) 123456789012345678901234L """ s = read_stringnl(f, decode=False, stripquotes=False) if not s.endswith("L"): raise ValueError("trailing 'L' required in %r" % s) return long(s) decimalnl_short = ArgumentDescriptor( name='decimalnl_short', n=UP_TO_NEWLINE, reader=read_decimalnl_short, doc="""A newline-terminated decimal integer literal. This never has a trailing 'L', and the integer fit in a short Python int on the box where the pickle was written -- but there's no guarantee it will fit in a short Python int on the box where the pickle is read. """) decimalnl_long = ArgumentDescriptor( name='decimalnl_long', n=UP_TO_NEWLINE, reader=read_decimalnl_long, doc="""A newline-terminated decimal integer literal. This has a trailing 'L', and can represent integers of any size. """) def read_floatnl(f): r""" >>> import StringIO >>> read_floatnl(StringIO.StringIO("-1.25\n6")) -1.25 """ s = read_stringnl(f, decode=False, stripquotes=False) return float(s) floatnl = ArgumentDescriptor( name='floatnl', n=UP_TO_NEWLINE, reader=read_floatnl, doc="""A newline-terminated decimal floating literal. In general this requires 17 significant digits for roundtrip identity, and pickling then unpickling infinities, NaNs, and minus zero doesn't work across boxes, or on some boxes even on itself (e.g., Windows can't read the strings it produces for infinities or NaNs). """) def read_float8(f): r""" >>> import StringIO, struct >>> raw = struct.pack(">d", -1.25) >>> raw '\xbf\xf4\x00\x00\x00\x00\x00\x00' >>> read_float8(StringIO.StringIO(raw + "\n")) -1.25 """ data = f.read(8) if len(data) == 8: return _unpack(">d", data)[0] raise ValueError("not enough data in stream to read float8") float8 = ArgumentDescriptor( name='float8', n=8, reader=read_float8, doc="""An 8-byte binary representation of a float, big-endian. The format is unique to Python, and shared with the struct module (format string '>d') "in theory" (the struct and cPickle implementations don't share the code -- they should). It's strongly related to the IEEE-754 double format, and, in normal cases, is in fact identical to the big-endian 754 double format. On other boxes the dynamic range is limited to that of a 754 double, and "add a half and chop" rounding is used to reduce the precision to 53 bits. However, even on a 754 box, infinities, NaNs, and minus zero may not be handled correctly (may not survive roundtrip pickling intact). """) # Protocol 2 formats from pickle import decode_long def read_long1(f): r""" >>> import StringIO >>> read_long1(StringIO.StringIO("\x00")) 0L >>> read_long1(StringIO.StringIO("\x02\xff\x00")) 255L >>> read_long1(StringIO.StringIO("\x02\xff\x7f")) 32767L >>> read_long1(StringIO.StringIO("\x02\x00\xff")) -256L >>> read_long1(StringIO.StringIO("\x02\x00\x80")) -32768L """ n = read_uint1(f) data = f.read(n) if len(data) != n: raise ValueError("not enough data in stream to read long1") return decode_long(data) long1 = ArgumentDescriptor( name="long1", n=TAKEN_FROM_ARGUMENT1, reader=read_long1, doc="""A binary long, little-endian, using 1-byte size. This first reads one byte as an unsigned size, then reads that many bytes and interprets them as a little-endian 2's-complement long. If the size is 0, that's taken as a shortcut for the long 0L. """) def read_long4(f): r""" >>> import StringIO >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00")) 255L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f")) 32767L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff")) -256L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80")) -32768L >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00")) 0L """ n = read_int4(f) if n < 0: raise ValueError("long4 byte count < 0: %d" % n) data = f.read(n) if len(data) != n: raise ValueError("not enough data in stream to read long4") return decode_long(data) long4 = ArgumentDescriptor( name="long4", n=TAKEN_FROM_ARGUMENT4, reader=read_long4, doc="""A binary representation of a long, little-endian. This first reads four bytes as a signed size (but requires the size to be >= 0), then reads that many bytes and interprets them as a little-endian 2's-complement long. If the size is 0, that's taken as a shortcut for the long 0L, although LONG1 should really be used then instead (and in any case where # of bytes < 256). """) ############################################################################## # Object descriptors. The stack used by the pickle machine holds objects, # and in the stack_before and stack_after attributes of OpcodeInfo # descriptors we need names to describe the various types of objects that can # appear on the stack. class StackObject(object): __slots__ = ( # name of descriptor record, for info only 'name', # type of object, or tuple of type objects (meaning the object can # be of any type in the tuple) 'obtype', # human-readable docs for this kind of stack object; a string 'doc', ) def __init__(self, name, obtype, doc): assert isinstance(name, str) self.name = name assert isinstance(obtype, type) or isinstance(obtype, tuple) if isinstance(obtype, tuple): for contained in obtype: assert isinstance(contained, type) self.obtype = obtype assert isinstance(doc, str) self.doc = doc def __repr__(self): return self.name pyint = StackObject( name='int', obtype=int, doc="A short (as opposed to long) Python integer object.") pylong = StackObject( name='long', obtype=long, doc="A long (as opposed to short) Python integer object.") pyinteger_or_bool = StackObject( name='int_or_bool', obtype=(int, long, bool), doc="A Python integer object (short or long), or " "a Python bool.") pybool = StackObject( name='bool', obtype=(bool,), doc="A Python bool object.") pyfloat = StackObject( name='float', obtype=float, doc="A Python float object.") pystring = StackObject( name='str', obtype=str, doc="A Python string object.") pyunicode = StackObject( name='unicode', obtype=unicode, doc="A Python Unicode string object.") pynone = StackObject( name="None", obtype=type(None), doc="The Python None object.") pytuple = StackObject( name="tuple", obtype=tuple, doc="A Python tuple object.") pylist = StackObject( name="list", obtype=list, doc="A Python list object.") pydict = StackObject( name="dict", obtype=dict, doc="A Python dict object.") anyobject = StackObject( name='any', obtype=object, doc="Any kind of object whatsoever.") markobject = StackObject( name="mark", obtype=StackObject, doc="""'The mark' is a unique object. Opcodes that operate on a variable number of objects generally don't embed the count of objects in the opcode, or pull it off the stack. Instead the MARK opcode is used to push a special marker object on the stack, and then some other opcodes grab all the objects from the top of the stack down to (but not including) the topmost marker object. """) stackslice = StackObject( name="stackslice", obtype=StackObject, doc="""An object representing a contiguous slice of the stack. This is used in conjuction with markobject, to represent all of the stack following the topmost markobject. For example, the POP_MARK opcode changes the stack from [..., markobject, stackslice] to [...] No matter how many object are on the stack after the topmost markobject, POP_MARK gets rid of all of them (including the topmost markobject too). """) ############################################################################## # Descriptors for pickle opcodes. class OpcodeInfo(object): __slots__ = ( # symbolic name of opcode; a string 'name', # the code used in a bytestream to represent the opcode; a # one-character string 'code', # If the opcode has an argument embedded in the byte string, an # instance of ArgumentDescriptor specifying its type. Note that # arg.reader(s) can be used to read and decode the argument from # the bytestream s, and arg.doc documents the format of the raw # argument bytes. If the opcode doesn't have an argument embedded # in the bytestream, arg should be None. 'arg', # what the stack looks like before this opcode runs; a list 'stack_before', # what the stack looks like after this opcode runs; a list 'stack_after', # the protocol number in which this opcode was introduced; an int 'proto', # human-readable docs for this opcode; a string 'doc', ) def __init__(self, name, code, arg, stack_before, stack_after, proto, doc): assert isinstance(name, str) self.name = name assert isinstance(code, str) assert len(code) == 1 self.code = code assert arg is None or isinstance(arg, ArgumentDescriptor) self.arg = arg assert isinstance(stack_before, list) for x in stack_before: assert isinstance(x, StackObject) self.stack_before = stack_before assert isinstance(stack_after, list) for x in stack_after: assert isinstance(x, StackObject) self.stack_after = stack_after assert isinstance(proto, int) and 0 <= proto <= 2 self.proto = proto assert isinstance(doc, str) self.doc = doc I = OpcodeInfo opcodes = [ # Ways to spell integers. I(name='INT', code='I', arg=decimalnl_short, stack_before=[], stack_after=[pyinteger_or_bool], proto=0, doc="""Push an integer or bool. The argument is a newline-terminated decimal literal string. The intent may have been that this always fit in a short Python int, but INT can be generated in pickles written on a 64-bit box that require a Python long on a 32-bit box. The difference between this and LONG then is that INT skips a trailing 'L', and produces a short int whenever possible. Another difference is due to that, when bool was introduced as a distinct type in 2.3, builtin names True and False were also added to 2.2.2, mapping to ints 1 and 0. For compatibility in both directions, True gets pickled as INT + "I01\\n", and False as INT + "I00\\n". Leading zeroes are never produced for a genuine integer. The 2.3 (and later) unpicklers special-case these and return bool instead; earlier unpicklers ignore the leading "0" and return the int. """), I(name='BININT', code='J', arg=int4, stack_before=[], stack_after=[pyint], proto=1, doc="""Push a four-byte signed integer. This handles the full range of Python (short) integers on a 32-bit box, directly as binary bytes (1 for the opcode and 4 for the integer). If the integer is non-negative and fits in 1 or 2 bytes, pickling via BININT1 or BININT2 saves space. """), I(name='BININT1', code='K', arg=uint1, stack_before=[], stack_after=[pyint], proto=1, doc="""Push a one-byte unsigned integer. This is a space optimization for pickling very small non-negative ints, in range(256). """), I(name='BININT2', code='M', arg=uint2, stack_before=[], stack_after=[pyint], proto=1, doc="""Push a two-byte unsigned integer. This is a space optimization for pickling small positive ints, in range(256, 2**16). Integers in range(256) can also be pickled via BININT2, but BININT1 instead saves a byte. """), I(name='LONG', code='L', arg=decimalnl_long, stack_before=[], stack_after=[pylong], proto=0, doc="""Push a long integer. The same as INT, except that the literal ends with 'L', and always unpickles to a Python long. There doesn't seem a real purpose to the trailing 'L'. Note that LONG takes time quadratic in the number of digits when unpickling (this is simply due to the nature of decimal->binary conversion). Proto 2 added linear-time (in C; still quadratic-time in Python) LONG1 and LONG4 opcodes. """), I(name="LONG1", code='\x8a', arg=long1, stack_before=[], stack_after=[pylong], proto=2, doc="""Long integer using one-byte length. A more efficient encoding of a Python long; the long1 encoding says it all."""), I(name="LONG4", code='\x8b', arg=long4, stack_before=[], stack_after=[pylong], proto=2, doc="""Long integer using found-byte length. A more efficient encoding of a Python long; the long4 encoding says it all."""), # Ways to spell strings (8-bit, not Unicode). I(name='STRING', code='S', arg=stringnl, stack_before=[], stack_after=[pystring], proto=0, doc="""Push a Python string object. The argument is a repr-style string, with bracketing quote characters, and perhaps embedded escapes. The argument extends until the next newline character. """), I(name='BINSTRING', code='T', arg=string4, stack_before=[], stack_after=[pystring], proto=1, doc="""Push a Python string object. There are two arguments: the first is a 4-byte little-endian signed int giving the number of bytes in the string, and the second is that many bytes, which are taken literally as the string content. """), I(name='SHORT_BINSTRING', code='U', arg=string1, stack_before=[], stack_after=[pystring], proto=1, doc="""Push a Python string object. There are two arguments: the first is a 1-byte unsigned int giving the number of bytes in the string, and the second is that many bytes, which are taken literally as the string content. """), # Ways to spell None. I(name='NONE', code='N', arg=None, stack_before=[], stack_after=[pynone], proto=0, doc="Push None on the stack."), # Ways to spell bools, starting with proto 2. See INT for how this was # done before proto 2. I(name='NEWTRUE', code='\x88', arg=None, stack_before=[], stack_after=[pybool], proto=2, doc="""True. Push True onto the stack."""), I(name='NEWFALSE', code='\x89', arg=None, stack_before=[], stack_after=[pybool], proto=2, doc="""True. Push False onto the stack."""), # Ways to spell Unicode strings. I(name='UNICODE', code='V', arg=unicodestringnl, stack_before=[], stack_after=[pyunicode], proto=0, # this may be pure-text, but it's a later addition doc="""Push a Python Unicode string object. The argument is a raw-unicode-escape encoding of a Unicode string, and so may contain embedded escape sequences. The argument extends until the next newline character. """), I(name='BINUNICODE', code='X', arg=unicodestring4, stack_before=[], stack_after=[pyunicode], proto=1, doc="""Push a Python Unicode string object. There are two arguments: the first is a 4-byte little-endian signed int giving the number of bytes in the string. The second is that many bytes, and is the UTF-8 encoding of the Unicode string. """), # Ways to spell floats. I(name='FLOAT', code='F', arg=floatnl, stack_before=[], stack_after=[pyfloat], proto=0, doc="""Newline-terminated decimal float literal. The argument is repr(a_float), and in general requires 17 significant digits for roundtrip conversion to be an identity (this is so for IEEE-754 double precision values, which is what Python float maps to on most boxes). In general, FLOAT cannot be used to transport infinities, NaNs, or minus zero across boxes (or even on a single box, if the platform C library can't read the strings it produces for such things -- Windows is like that), but may do less damage than BINFLOAT on boxes with greater precision or dynamic range than IEEE-754 double. """), I(name='BINFLOAT', code='G', arg=float8, stack_before=[], stack_after=[pyfloat], proto=1, doc="""Float stored in binary form, with 8 bytes of data. This generally requires less than half the space of FLOAT encoding. In general, BINFLOAT cannot be used to transport infinities, NaNs, or minus zero, raises an exception if the exponent exceeds the range of an IEEE-754 double, and retains no more than 53 bits of precision (if there are more than that, "add a half and chop" rounding is used to cut it back to 53 significant bits). """), # Ways to build lists. I(name='EMPTY_LIST', code=']', arg=None, stack_before=[], stack_after=[pylist], proto=1, doc="Push an empty list."), I(name='APPEND', code='a', arg=None, stack_before=[pylist, anyobject], stack_after=[pylist], proto=0, doc="""Append an object to a list. Stack before: ... pylist anyobject Stack after: ... pylist+[anyobject] although pylist is really extended in-place. """), I(name='APPENDS', code='e', arg=None, stack_before=[pylist, markobject, stackslice], stack_after=[pylist], proto=1, doc="""Extend a list by a slice of stack objects. Stack before: ... pylist markobject stackslice Stack after: ... pylist+stackslice although pylist is really extended in-place. """), I(name='LIST', code='l', arg=None, stack_before=[markobject, stackslice], stack_after=[pylist], proto=0, doc="""Build a list out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python list, which single list object replaces all of the stack from the topmost markobject onward. For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... [1, 2, 3, 'abc'] """), # Ways to build tuples. I(name='EMPTY_TUPLE', code=')', arg=None, stack_before=[], stack_after=[pytuple], proto=1, doc="Push an empty tuple."), I(name='TUPLE', code='t', arg=None, stack_before=[markobject, stackslice], stack_after=[pytuple], proto=0, doc="""Build a tuple out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python tuple, which single tuple object replaces all of the stack from the topmost markobject onward. For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... (1, 2, 3, 'abc') """), I(name='TUPLE1', code='\x85', arg=None, stack_before=[anyobject], stack_after=[pytuple], proto=2, doc="""One-tuple. This code pops one value off the stack and pushes a tuple of length 1 whose one item is that value back onto it. IOW: stack[-1] = tuple(stack[-1:]) """), I(name='TUPLE2', code='\x86', arg=None, stack_before=[anyobject, anyobject], stack_after=[pytuple], proto=2, doc="""One-tuple. This code pops two values off the stack and pushes a tuple of length 2 whose items are those values back onto it. IOW: stack[-2:] = [tuple(stack[-2:])] """), I(name='TUPLE3', code='\x87', arg=None, stack_before=[anyobject, anyobject, anyobject], stack_after=[pytuple], proto=2, doc="""One-tuple. This code pops three values off the stack and pushes a tuple of length 3 whose items are those values back onto it. IOW: stack[-3:] = [tuple(stack[-3:])] """), # Ways to build dicts. I(name='EMPTY_DICT', code='}', arg=None, stack_before=[], stack_after=[pydict], proto=1, doc="Push an empty dict."), I(name='DICT', code='d', arg=None, stack_before=[markobject, stackslice], stack_after=[pydict], proto=0, doc="""Build a dict out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python dict, which single dict object replaces all of the stack from the topmost markobject onward. The stack slice alternates key, value, key, value, .... For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... {1: 2, 3: 'abc'} """), I(name='SETITEM', code='s', arg=None, stack_before=[pydict, anyobject, anyobject], stack_after=[pydict], proto=0, doc="""Add a key+value pair to an existing dict. Stack before: ... pydict key value Stack after: ... pydict where pydict has been modified via pydict[key] = value. """), I(name='SETITEMS', code='u', arg=None, stack_before=[pydict, markobject, stackslice], stack_after=[pydict], proto=1, doc="""Add an arbitrary number of key+value pairs to an existing dict. The slice of the stack following the topmost markobject is taken as an alternating sequence of keys and values, added to the dict immediately under the topmost markobject. Everything at and after the topmost markobject is popped, leaving the mutated dict at the top of the stack. Stack before: ... pydict markobject key_1 value_1 ... key_n value_n Stack after: ... pydict where pydict has been modified via pydict[key_i] = value_i for i in 1, 2, ..., n, and in that order. """), # Stack manipulation. I(name='POP', code='0', arg=None, stack_before=[anyobject], stack_after=[], proto=0, doc="Discard the top stack item, shrinking the stack by one item."), I(name='DUP', code='2', arg=None, stack_before=[anyobject], stack_after=[anyobject, anyobject], proto=0, doc="Push the top stack item onto the stack again, duplicating it."), I(name='MARK', code='(', arg=None, stack_before=[], stack_after=[markobject], proto=0, doc="""Push markobject onto the stack. markobject is a unique object, used by other opcodes to identify a region of the stack containing a variable number of objects for them to work on. See markobject.doc for more detail. """), I(name='POP_MARK', code='1', arg=None, stack_before=[markobject, stackslice], stack_after=[], proto=0, doc="""Pop all the stack objects at and above the topmost markobject. When an opcode using a variable number of stack objects is done, POP_MARK is used to remove those objects, and to remove the markobject that delimited their starting position on the stack. """), # Memo manipulation. There are really only two operations (get and put), # each in all-text, "short binary", and "long binary" flavors. I(name='GET', code='g', arg=decimalnl_short, stack_before=[], stack_after=[anyobject], proto=0, doc="""Read an object from the memo and push it on the stack. The index of the memo object to push is given by the newline-teriminated decimal string following. BINGET and LONG_BINGET are space-optimized versions. """), I(name='BINGET', code='h', arg=uint1, stack_before=[], stack_after=[anyobject], proto=1, doc="""Read an object from the memo and push it on the stack. The index of the memo object to push is given by the 1-byte unsigned integer following. """), I(name='LONG_BINGET', code='j', arg=int4, stack_before=[], stack_after=[anyobject], proto=1, doc="""Read an object from the memo and push it on the stack. The index of the memo object to push is given by the 4-byte signed little-endian integer following. """), I(name='PUT', code='p', arg=decimalnl_short, stack_before=[], stack_after=[], proto=0, doc="""Store the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the newline- terminated decimal string following. BINPUT and LONG_BINPUT are space-optimized versions. """), I(name='BINPUT', code='q', arg=uint1, stack_before=[], stack_after=[], proto=1, doc="""Store the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the 1-byte unsigned integer following. """), I(name='LONG_BINPUT', code='r', arg=int4, stack_before=[], stack_after=[], proto=1, doc="""Store the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the 4-byte signed little-endian integer following. """), # Access the extension registry (predefined objects). Akin to the GET # family. I(name='EXT1', code='\x82', arg=uint1, stack_before=[], stack_after=[anyobject], proto=2, doc="""Extension code. This code and the similar EXT2 and EXT4 allow using a registry of popular objects that are pickled by name, typically classes. It is envisioned that through a global negotiation and registration process, third parties can set up a mapping between ints and object names. In order to guarantee pickle interchangeability, the extension code registry ought to be global, although a range of codes may be reserved for private use. EXT1 has a 1-byte integer argument. This is used to index into the extension registry, and the object at that index is pushed on the stack. """), I(name='EXT2', code='\x83', arg=uint2, stack_before=[], stack_after=[anyobject], proto=2, doc="""Extension code. See EXT1. EXT2 has a two-byte integer argument. """), I(name='EXT4', code='\x84', arg=int4, stack_before=[], stack_after=[anyobject], proto=2, doc="""Extension code. See EXT1. EXT4 has a four-byte integer argument. """), # Push a class object, or module function, on the stack, via its module # and name. I(name='GLOBAL', code='c', arg=stringnl_noescape_pair, stack_before=[], stack_after=[anyobject], proto=0, doc="""Push a global object (module.attr) on the stack. Two newline-terminated strings follow the GLOBAL opcode. The first is taken as a module name, and the second as a class name. The class object module.class is pushed on the stack. More accurately, the object returned by self.find_class(module, class) is pushed on the stack, so unpickling subclasses can override this form of lookup. """), # Ways to build objects of classes pickle doesn't know about directly # (user-defined classes). I despair of documenting this accurately # and comprehensibly -- you really have to read the pickle code to # find all the special cases. I(name='REDUCE', code='R', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=0, doc="""Push an object built from a callable and an argument tuple. The opcode is named to remind of the __reduce__() method. Stack before: ... callable pytuple Stack after: ... callable(*pytuple) The callable and the argument tuple are the first two items returned by a __reduce__ method. Applying the callable to the argtuple is supposed to reproduce the original object, or at least get it started. If the __reduce__ method returns a 3-tuple, the last component is an argument to be passed to the object's __setstate__, and then the REDUCE opcode is followed by code to create setstate's argument, and then a BUILD opcode to apply __setstate__ to that argument. There are lots of special cases here. The argtuple can be None, in which case callable.__basicnew__() is called instead to produce the object to be pushed on the stack. This appears to be a trick unique to ExtensionClasses, and is deprecated regardless. If type(callable) is not ClassType, REDUCE complains unless the callable has been registered with the copy_reg module's safe_constructors dict, or the callable has a magic '__safe_for_unpickling__' attribute with a true value. I'm not sure why it does this, but I've sure seen this complaint often enough when I didn't want to <wink>. """), I(name='BUILD', code='b', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=0, doc="""Finish building an object, via __setstate__ or dict update. Stack before: ... anyobject argument Stack after: ... anyobject where anyobject may have been mutated, as follows: If the object has a __setstate__ method, anyobject.__setstate__(argument) is called. Else the argument must be a dict, the object must have a __dict__, and the object is updated via anyobject.__dict__.update(argument) This may raise RuntimeError in restricted execution mode (which disallows access to __dict__ directly); in that case, the object is updated instead via for k, v in argument.items(): anyobject[k] = v """), I(name='INST', code='i', arg=stringnl_noescape_pair, stack_before=[markobject, stackslice], stack_after=[anyobject], proto=0, doc="""Build a class instance. This is the protocol 0 version of protocol 1's OBJ opcode. INST is followed by two newline-terminated strings, giving a module and class name, just as for the GLOBAL opcode (and see GLOBAL for more details about that). self.find_class(module, name) is used to get a class object. In addition, all the objects on the stack following the topmost markobject are gathered into a tuple and popped (along with the topmost markobject), just as for the TUPLE opcode. Now it gets complicated. If all of these are true: + The argtuple is empty (markobject was at the top of the stack at the start). + It's an old-style class object (the type of the class object is ClassType). + The class object does not have a __getinitargs__ attribute. then we want to create an old-style class instance without invoking its __init__() method (pickle has waffled on this over the years; not calling __init__() is current wisdom). In this case, an instance of an old-style dummy class is created, and then we try to rebind its __class__ attribute to the desired class object. If this succeeds, the new instance object is pushed on the stack, and we're done. In restricted execution mode it can fail (assignment to __class__ is disallowed), and I'm not really sure what happens then -- it looks like the code ends up calling the class object's __init__ anyway, via falling into the next case. Else (the argtuple is not empty, it's not an old-style class object, or the class object does have a __getinitargs__ attribute), the code first insists that the class object have a __safe_for_unpickling__ attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE, it doesn't matter whether this attribute has a true or false value, it only matters whether it exists (XXX this is a bug; cPickle requires the attribute to be true). If __safe_for_unpickling__ doesn't exist, UnpicklingError is raised. Else (the class object does have a __safe_for_unpickling__ attr), the class object obtained from INST's arguments is applied to the argtuple obtained from the stack, and the resulting instance object is pushed on the stack. NOTE: checks for __safe_for_unpickling__ went away in Python 2.3. """), I(name='OBJ', code='o', arg=None, stack_before=[markobject, anyobject, stackslice], stack_after=[anyobject], proto=1, doc="""Build a class instance. This is the protocol 1 version of protocol 0's INST opcode, and is very much like it. The major difference is that the class object is taken off the stack, allowing it to be retrieved from the memo repeatedly if several instances of the same class are created. This can be much more efficient (in both time and space) than repeatedly embedding the module and class names in INST opcodes. Unlike INST, OBJ takes no arguments from the opcode stream. Instead the class object is taken off the stack, immediately above the topmost markobject: Stack before: ... markobject classobject stackslice Stack after: ... new_instance_object As for INST, the remainder of the stack above the markobject is gathered into an argument tuple, and then the logic seems identical, except that no __safe_for_unpickling__ check is done (XXX this is a bug; cPickle does test __safe_for_unpickling__). See INST for the gory details. NOTE: In Python 2.3, INST and OBJ are identical except for how they get the class object. That was always the intent; the implementations had diverged for accidental reasons. """), I(name='NEWOBJ', code='\x81', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=2, doc="""Build an object instance. The stack before should be thought of as containing a class object followed by an argument tuple (the tuple being the stack top). Call these cls and args. They are popped off the stack, and the value returned by cls.__new__(cls, *args) is pushed back onto the stack. """), # Machine control. I(name='PROTO', code='\x80', arg=uint1, stack_before=[], stack_after=[], proto=2, doc="""Protocol version indicator. For protocol 2 and above, a pickle must start with this opcode. The argument is the protocol version, an int in range(2, 256). """), I(name='STOP', code='.', arg=None, stack_before=[anyobject], stack_after=[], proto=0, doc="""Stop the unpickling machine. Every pickle ends with this opcode. The object at the top of the stack is popped, and that's the result of unpickling. The stack should be empty then. """), # Ways to deal with persistent IDs. I(name='PERSID', code='P', arg=stringnl_noescape, stack_before=[], stack_after=[anyobject], proto=0, doc="""Push an object identified by a persistent ID. The pickle module doesn't define what a persistent ID means. PERSID's argument is a newline-terminated str-style (no embedded escapes, no bracketing quote characters) string, which *is* "the persistent ID". The unpickler passes this string to self.persistent_load(). Whatever object that returns is pushed on the stack. There is no implementation of persistent_load() in Python's unpickler: it must be supplied by an unpickler subclass. """), I(name='BINPERSID', code='Q', arg=None, stack_before=[anyobject], stack_after=[anyobject], proto=1, doc="""Push an object identified by a persistent ID. Like PERSID, except the persistent ID is popped off the stack (instead of being a string embedded in the opcode bytestream). The persistent ID is passed to self.persistent_load(), and whatever object that returns is pushed on the stack. See PERSID for more detail. """), ] del I # Verify uniqueness of .name and .code members. name2i = {} code2i = {} for i, d in enumerate(opcodes): if d.name in name2i: raise ValueError("repeated name %r at indices %d and %d" % (d.name, name2i[d.name], i)) if d.code in code2i: raise ValueError("repeated code %r at indices %d and %d" % (d.code, code2i[d.code], i)) name2i[d.name] = i code2i[d.code] = i del name2i, code2i, i, d ############################################################################## # Build a code2op dict, mapping opcode characters to OpcodeInfo records. # Also ensure we've got the same stuff as pickle.py, although the # introspection here is dicey. code2op = {} for d in opcodes: code2op[d.code] = d del d def assure_pickle_consistency(verbose=False): import pickle, re copy = code2op.copy() for name in pickle.__all__: if not re.match("[A-Z][A-Z0-9_]+$", name): if verbose: print "skipping %r: it doesn't look like an opcode name" % name continue picklecode = getattr(pickle, name) if not isinstance(picklecode, str) or len(picklecode) != 1: if verbose: print ("skipping %r: value %r doesn't look like a pickle " "code" % (name, picklecode)) continue if picklecode in copy: if verbose: print "checking name %r w/ code %r for consistency" % ( name, picklecode) d = copy[picklecode] if d.name != name: raise ValueError("for pickle code %r, pickle.py uses name %r " "but we're using name %r" % (picklecode, name, d.name)) # Forget this one. Any left over in copy at the end are a problem # of a different kind. del copy[picklecode] else: raise ValueError("pickle.py appears to have a pickle opcode with " "name %r and code %r, but we don't" % (name, picklecode)) if copy: msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"] for code, d in copy.items(): msg.append(" name %r with code %r" % (d.name, code)) raise ValueError("\n".join(msg)) assure_pickle_consistency() del assure_pickle_consistency ############################################################################## # A pickle opcode generator. def genops(pickle): """Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a string object, it's wrapped in a StringIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None. """ import cStringIO as StringIO if isinstance(pickle, str): pickle = StringIO.StringIO(pickle) if hasattr(pickle, "tell"): getpos = pickle.tell else: getpos = lambda: None while True: pos = getpos() code = pickle.read(1) opcode = code2op.get(code) if opcode is None: if code == "": raise ValueError("pickle exhausted before seeing STOP") else: raise ValueError("at position %s, opcode %r unknown" % ( pos is None and "<unknown>" or pos, code)) if opcode.arg is None: arg = None else: arg = opcode.arg.reader(pickle) yield opcode, arg, pos if code == '.': assert opcode.name == 'STOP' break ############################################################################## # A symbolic pickle disassembler. def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack) _dis_test = r""" >>> import pickle >>> x = [1, 2, (3, 4), {'abc': u"def"}] >>> pkl = pickle.dumps(x, 0) >>> dis(pkl) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: I INT 1 8: a APPEND 9: I INT 2 12: a APPEND 13: ( MARK 14: I INT 3 17: I INT 4 20: t TUPLE (MARK at 13) 21: p PUT 1 24: a APPEND 25: ( MARK 26: d DICT (MARK at 25) 27: p PUT 2 30: S STRING 'abc' 37: p PUT 3 40: V UNICODE u'def' 45: p PUT 4 48: s SETITEM 49: a APPEND 50: . STOP highest protocol among opcodes = 0 Try again with a "binary" pickle. >>> pkl = pickle.dumps(x, 1) >>> dis(pkl) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: K BININT1 1 6: K BININT1 2 8: ( MARK 9: K BININT1 3 11: K BININT1 4 13: t TUPLE (MARK at 8) 14: q BINPUT 1 16: } EMPTY_DICT 17: q BINPUT 2 19: U SHORT_BINSTRING 'abc' 24: q BINPUT 3 26: X BINUNICODE u'def' 34: q BINPUT 4 36: s SETITEM 37: e APPENDS (MARK at 3) 38: . STOP highest protocol among opcodes = 1 Exercise the INST/OBJ/BUILD family. >>> dis(pickle.dumps(zip, 0)) 0: c GLOBAL '__builtin__ zip' 17: p PUT 0 20: . STOP highest protocol among opcodes = 0 >>> x = [pickle.PicklingError()] * 2 >>> dis(pickle.dumps(x, 0)) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: ( MARK 6: i INST 'pickle PicklingError' (MARK at 5) 28: p PUT 1 31: ( MARK 32: d DICT (MARK at 31) 33: p PUT 2 36: S STRING 'args' 44: p PUT 3 47: ( MARK 48: t TUPLE (MARK at 47) 49: s SETITEM 50: b BUILD 51: a APPEND 52: g GET 1 55: a APPEND 56: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(x, 1)) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: ( MARK 5: c GLOBAL 'pickle PicklingError' 27: q BINPUT 1 29: o OBJ (MARK at 4) 30: q BINPUT 2 32: } EMPTY_DICT 33: q BINPUT 3 35: U SHORT_BINSTRING 'args' 41: q BINPUT 4 43: ) EMPTY_TUPLE 44: s SETITEM 45: b BUILD 46: h BINGET 2 48: e APPENDS (MARK at 3) 49: . STOP highest protocol among opcodes = 1 Try "the canonical" recursive-object test. >>> L = [] >>> T = L, >>> L.append(T) >>> L[0] is T True >>> T[0] is L True >>> L[0][0] is L True >>> T[0][0] is T True >>> dis(pickle.dumps(L, 0)) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: ( MARK 6: g GET 0 9: t TUPLE (MARK at 5) 10: p PUT 1 13: a APPEND 14: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(L, 1)) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: h BINGET 0 6: t TUPLE (MARK at 3) 7: q BINPUT 1 9: a APPEND 10: . STOP highest protocol among opcodes = 1 Note that, in the protocol 0 pickle of the recursive tuple, the disassembler has to emulate the stack in order to realize that the POP opcode at 16 gets rid of the MARK at 0. >>> dis(pickle.dumps(T, 0)) 0: ( MARK 1: ( MARK 2: l LIST (MARK at 1) 3: p PUT 0 6: ( MARK 7: g GET 0 10: t TUPLE (MARK at 6) 11: p PUT 1 14: a APPEND 15: 0 POP 16: 0 POP (MARK at 0) 17: g GET 1 20: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(T, 1)) 0: ( MARK 1: ] EMPTY_LIST 2: q BINPUT 0 4: ( MARK 5: h BINGET 0 7: t TUPLE (MARK at 4) 8: q BINPUT 1 10: a APPEND 11: 1 POP_MARK (MARK at 0) 12: h BINGET 1 14: . STOP highest protocol among opcodes = 1 Try protocol 2. >>> dis(pickle.dumps(L, 2)) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: h BINGET 0 7: \x85 TUPLE1 8: q BINPUT 1 10: a APPEND 11: . STOP highest protocol among opcodes = 2 >>> dis(pickle.dumps(T, 2)) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: h BINGET 0 7: \x85 TUPLE1 8: q BINPUT 1 10: a APPEND 11: 0 POP 12: h BINGET 1 14: . STOP highest protocol among opcodes = 2 """ _memo_test = r""" >>> import pickle >>> from StringIO import StringIO >>> f = StringIO() >>> p = pickle.Pickler(f, 2) >>> x = [1, 2, 3] >>> p.dump(x) >>> p.dump(x) >>> f.seek(0) >>> memo = {} >>> dis(f, memo=memo) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: ( MARK 6: K BININT1 1 8: K BININT1 2 10: K BININT1 3 12: e APPENDS (MARK at 5) 13: . STOP highest protocol among opcodes = 2 >>> dis(f, memo=memo) 14: \x80 PROTO 2 16: h BINGET 0 18: . STOP highest protocol among opcodes = 2 """ __test__ = {'disassembler_test': _dis_test, 'disassembler_memo_test': _memo_test, } def _test(): import doctest return doctest.testmod() if __name__ == "__main__": _test()
Python
# Module doctest. # Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org). # Major enhancements and refactoring by: # Jim Fulton # Edward Loper # Provided as-is; use at your own risk; no warranty; no promises; enjoy! r"""Module doctest -- a framework for running examples in docstrings. In simplest use, end each module M to be tested with: def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() Then running the module as a script will cause the examples in the docstrings to get executed and verified: python M.py This won't display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout (why not stderr? because stderr is a lame hack <0.2 wink>), and the final line of output is "Test failed.". Run it with the -v switch instead: python M.py -v and a detailed report of all examples tried is printed to stdout, along with assorted summaries at the end. You can force verbose mode by passing "verbose=True" to testmod, or prohibit it by passing "verbose=False". In either of those cases, sys.argv is not examined by testmod. There are a variety of other ways to run doctests, including integration with the unittest framework, and support for running non-Python text files containing doctests. There are also many ways to override parts of doctest's default behaviors. See the Library Reference Manual for details. """ __docformat__ = 'reStructuredText en' __all__ = [ # 0, Option Flags 'register_optionflag', 'DONT_ACCEPT_TRUE_FOR_1', 'DONT_ACCEPT_BLANKLINE', 'NORMALIZE_WHITESPACE', 'ELLIPSIS', 'IGNORE_EXCEPTION_DETAIL', 'COMPARISON_FLAGS', 'REPORT_UDIFF', 'REPORT_CDIFF', 'REPORT_NDIFF', 'REPORT_ONLY_FIRST_FAILURE', 'REPORTING_FLAGS', # 1. Utility Functions 'is_private', # 2. Example & DocTest 'Example', 'DocTest', # 3. Doctest Parser 'DocTestParser', # 4. Doctest Finder 'DocTestFinder', # 5. Doctest Runner 'DocTestRunner', 'OutputChecker', 'DocTestFailure', 'UnexpectedException', 'DebugRunner', # 6. Test Functions 'testmod', 'testfile', 'run_docstring_examples', # 7. Tester 'Tester', # 8. Unittest Support 'DocTestSuite', 'DocFileSuite', 'set_unittest_reportflags', # 9. Debugging Support 'script_from_examples', 'testsource', 'debug_src', 'debug', ] import __future__ import sys, traceback, inspect, linecache, os, re, types import unittest, difflib, pdb, tempfile import warnings from StringIO import StringIO # Don't whine about the deprecated is_private function in this # module's tests. warnings.filterwarnings("ignore", "is_private", DeprecationWarning, __name__, 0) # There are 4 basic classes: # - Example: a <source, want> pair, plus an intra-docstring line number. # - DocTest: a collection of examples, parsed from a docstring, plus # info about where the docstring came from (name, filename, lineno). # - DocTestFinder: extracts DocTests from a given object's docstring and # its contained objects' docstrings. # - DocTestRunner: runs DocTest cases, and accumulates statistics. # # So the basic picture is: # # list of: # +------+ +---------+ +-------+ # |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results| # +------+ +---------+ +-------+ # | Example | # | ... | # | Example | # +---------+ # Option constants. OPTIONFLAGS_BY_NAME = {} def register_optionflag(name): flag = 1 << len(OPTIONFLAGS_BY_NAME) OPTIONFLAGS_BY_NAME[name] = flag return flag DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1') DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE') NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE') ELLIPSIS = register_optionflag('ELLIPSIS') IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL') COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | IGNORE_EXCEPTION_DETAIL) REPORT_UDIFF = register_optionflag('REPORT_UDIFF') REPORT_CDIFF = register_optionflag('REPORT_CDIFF') REPORT_NDIFF = register_optionflag('REPORT_NDIFF') REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE') REPORTING_FLAGS = (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE) # Special string markers for use in `want` strings: BLANKLINE_MARKER = '<BLANKLINE>' ELLIPSIS_MARKER = '...' ###################################################################### ## Table of Contents ###################################################################### # 1. Utility Functions # 2. Example & DocTest -- store test cases # 3. DocTest Parser -- extracts examples from strings # 4. DocTest Finder -- extracts test cases from objects # 5. DocTest Runner -- runs test cases # 6. Test Functions -- convenient wrappers for testing # 7. Tester Class -- for backwards compatibility # 8. Unittest Support # 9. Debugging Support # 10. Example Usage ###################################################################### ## 1. Utility Functions ###################################################################### def is_private(prefix, base): """prefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (at least one) underscore, but does not both begin and end with (at least) two underscores. >>> is_private("a.b", "my_func") False >>> is_private("____", "_my_func") True >>> is_private("someclass", "__init__") False >>> is_private("sometypo", "__init_") True >>> is_private("x.y.z", "_") True >>> is_private("_x.y.z", "__") False >>> is_private("", "") # senseless but consistent False """ warnings.warn("is_private is deprecated; it wasn't useful; " "examine DocTestFinder.find() lists instead", DeprecationWarning, stacklevel=2) return base[:1] == "_" and not base[:2] == "__" == base[-2:] def _extract_future_flags(globs): """ Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). """ flags = 0 for fname in __future__.all_feature_names: feature = globs.get(fname, None) if feature is getattr(__future__, fname): flags |= feature.compiler_flag return flags def _normalize_module(module, depth=2): """ Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. The calling module is assumed to be the module of the stack frame at the given depth in the call stack. """ if inspect.ismodule(module): return module elif isinstance(module, (str, unicode)): return __import__(module, globals(), locals(), ["*"]) elif module is None: return sys.modules[sys._getframe(depth).f_globals['__name__']] else: raise TypeError("Expected a module, string, or None") def _indent(s, indent=4): """ Add the given number of space characters to the beginning every non-blank line in `s`, and return the result. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) def _exception_traceback(exc_info): """ Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). """ # Get a traceback message. excout = StringIO() exc_type, exc_val, exc_tb = exc_info traceback.print_exception(exc_type, exc_val, exc_tb, file=excout) return excout.getvalue() # Override some StringIO methods. class _SpoofOut(StringIO): def getvalue(self): result = StringIO.getvalue(self) # If anything at all was written, make sure there's a trailing # newline. There's no way for the expected output to indicate # that a trailing newline is missing. if result and not result.endswith("\n"): result += "\n" # Prevent softspace from screwing up the next test case, in # case they used print with a trailing comma in an example. if hasattr(self, "softspace"): del self.softspace return result def truncate(self, size=None): StringIO.truncate(self, size) if hasattr(self, "softspace"): del self.softspace # Worst-case linear-time ellipsis matching. def _ellipsis_match(want, got): """ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False """ if ELLIPSIS_MARKER not in want: return want == got # Find "the real" strings. ws = want.split(ELLIPSIS_MARKER) assert len(ws) >= 2 # Deal with exact matches possibly needed at one or both ends. startpos, endpos = 0, len(got) w = ws[0] if w: # starts with exact match if got.startswith(w): startpos = len(w) del ws[0] else: return False w = ws[-1] if w: # ends with exact match if got.endswith(w): endpos -= len(w) del ws[-1] else: return False if startpos > endpos: # Exact end matches required more characters than we have, as in # _ellipsis_match('aa...aa', 'aaa') return False # For the rest, we only need to find the leftmost non-overlapping # match for each piece. If there's no overall match that way alone, # there's no overall match period. for w in ws: # w may be '' at times, if there are consecutive ellipses, or # due to an ellipsis at the start or end of `want`. That's OK. # Search for an empty string succeeds, and doesn't change startpos. startpos = got.find(w, startpos, endpos) if startpos < 0: return False startpos += len(w) return True def _comment_line(line): "Return a commented form of the given line" line = line.rstrip() if line: return '# '+line else: return '#' class _OutputRedirectingPdb(pdb.Pdb): """ A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. """ def __init__(self, out): self.__out = out pdb.Pdb.__init__(self) def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout # [XX] Normalize with respect to os.path.pardir? def _module_relative_path(module, path): if not inspect.ismodule(module): raise TypeError, 'Expected a module: %r' % module if path.startswith('/'): raise ValueError, 'Module-relative files may not have absolute paths' # Find the base directory for the path. if hasattr(module, '__file__'): # A normal module/package basedir = os.path.split(module.__file__)[0] elif module.__name__ == '__main__': # An interactive session. if len(sys.argv)>0 and sys.argv[0] != '': basedir = os.path.split(sys.argv[0])[0] else: basedir = os.curdir else: # A module w/o __file__ (this includes builtins) raise ValueError("Can't resolve paths relative to the module " + module + " (it has no __file__)") # Combine the base directory and the path. return os.path.join(basedir, *(path.split('/'))) ###################################################################### ## 2. Example & DocTest ###################################################################### ## - An "example" is a <source, want> pair, where "source" is a ## fragment of source code, and "want" is the expected output for ## "source." The Example class also includes information about ## where the example was extracted from. ## ## - A "doctest" is a collection of examples, typically extracted from ## a string (such as an object's docstring). The DocTest class also ## includes information about where the string was extracted from. class Example: """ A single doctest example, consisting of source code and expected output. `Example` defines the following attributes: - source: A single Python statement, always ending with a newline. The constructor adds a newline if needed. - want: The expected output from running the source code (either from stdout, or a traceback in case of exception). `want` ends with a newline unless it's empty, in which case it's an empty string. The constructor adds a newline if needed. - exc_msg: The exception message generated by the example, if the example is expected to generate an exception; or `None` if it is not expected to generate an exception. This exception message is compared against the return value of `traceback.format_exception_only()`. `exc_msg` ends with a newline unless it's `None`. The constructor adds a newline if needed. - lineno: The line number within the DocTest string containing this Example where the Example begins. This line number is zero-based, with respect to the beginning of the DocTest. - indent: The example's indentation in the DocTest string. I.e., the number of space characters that preceed the example's first prompt. - options: A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner's optionflags). By default, no options are set. """ def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, options=None): # Normalize inputs. if not source.endswith('\n'): source += '\n' if want and not want.endswith('\n'): want += '\n' if exc_msg is not None and not exc_msg.endswith('\n'): exc_msg += '\n' # Store properties. self.source = source self.want = want self.lineno = lineno self.indent = indent if options is None: options = {} self.options = options self.exc_msg = exc_msg class DocTest: """ A collection of doctest examples that should be run in a single namespace. Each `DocTest` defines the following attributes: - examples: the list of examples. - globs: The namespace (aka globals) that the examples should be run in. - name: A name identifying the DocTest (typically, the name of the object whose docstring this DocTest was extracted from). - filename: The name of the file that this DocTest was extracted from, or `None` if the filename is unknown. - lineno: The line number within filename where this DocTest begins, or `None` if the line number is unavailable. This line number is zero-based, with respect to the beginning of the file. - docstring: The string that the examples were extracted from, or `None` if the string is unavailable. """ def __init__(self, examples, globs, name, filename, lineno, docstring): """ Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. """ assert not isinstance(examples, basestring), \ "DocTest no longer accepts str; use DocTestParser instead" self.examples = examples self.docstring = docstring self.globs = globs.copy() self.name = name self.filename = filename self.lineno = lineno def __repr__(self): if len(self.examples) == 0: examples = 'no examples' elif len(self.examples) == 1: examples = '1 example' else: examples = '%d examples' % len(self.examples) return ('<DocTest %s from %s:%s (%s)>' % (self.name, self.filename, self.lineno, examples)) # This lets us sort tests by name: def __cmp__(self, other): if not isinstance(other, DocTest): return -1 return cmp((self.name, self.filename, self.lineno, id(self)), (other.name, other.filename, other.lineno, id(other))) ###################################################################### ## 3. DocTestParser ###################################################################### class DocTestParser: """ A class used to parse strings containing doctest examples. """ # This regular expression is used to find doctest examples in a # string. It defines three groups: `source` is the source code # (including leading indentation and prompts); `indent` is the # indentation of the first (PS1) line of the source code; and # `want` is the expected output (including leading indentation). _EXAMPLE_RE = re.compile(r''' # Source consists of a PS1 line followed by zero or more PS2 lines. (?P<source> (?:^(?P<indent> [ ]*) >>> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P<want> (?:(?![ ]*$) # Not a blank line (?![ ]*>>>) # Not a line starting with PS1 .*$\n? # But any other line )*) ''', re.MULTILINE | re.VERBOSE) # A regular expression for handling `want` strings that contain # expected exceptions. It divides `want` into three pieces: # - the traceback header line (`hdr`) # - the traceback stack (`stack`) # - the exception message (`msg`), as generated by # traceback.format_exception_only() # `msg` may have multiple lines. We assume/require that the # exception message is the first non-indented line starting with a word # character following the traceback header line. _EXCEPTION_RE = re.compile(r""" # Grab the traceback header. Different versions of Python have # said different things on the first traceback line. ^(?P<hdr> Traceback\ \( (?: most\ recent\ call\ last | innermost\ last ) \) : ) \s* $ # toss trailing whitespace on the header. (?P<stack> .*?) # don't blink: absorb stuff until... ^ (?P<msg> \w+ .*) # a line *starts* with alphanum. """, re.VERBOSE | re.MULTILINE | re.DOTALL) # A callable returning a true value iff its argument is a blank line # or contains a single comment. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match def parse(self, string, name='<string>'): """ Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages. """ string = string.expandtabs() # If all lines begin with the same indentation, then strip it. min_indent = self._min_indent(string) if min_indent > 0: string = '\n'.join([l[min_indent:] for l in string.split('\n')]) output = [] charno, lineno = 0, 0 # Find all doctest examples in the string: for m in self._EXAMPLE_RE.finditer(string): # Add the pre-example text to `output`. output.append(string[charno:m.start()]) # Update lineno (lines before this example) lineno += string.count('\n', charno, m.start()) # Extract info from the regexp match. (source, options, want, exc_msg) = \ self._parse_example(m, name, lineno) # Create an Example, and add it to the list. if not self._IS_BLANK_OR_COMMENT(source): output.append( Example(source, want, exc_msg, lineno=lineno, indent=min_indent+len(m.group('indent')), options=options) ) # Update lineno (lines inside this example) lineno += string.count('\n', m.start(), m.end()) # Update charno. charno = m.end() # Add any remaining post-example text to `output`. output.append(string[charno:]) return output def get_doctest(self, string, globs, name, filename, lineno): """ Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information. """ return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string) def get_examples(self, string, name='<string>'): """ Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it's most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called \"line 1\" then. The optional argument `name` is a name identifying this string, and is only used for error messages. """ return [x for x in self.parse(string, name) if isinstance(x, Example)] def _parse_example(self, m, name, lineno): """ Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example's source code (with prompts and indentation stripped); and `want` is the example's expected output (with indentation stripped). `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ # Get the example's indentation level. indent = len(m.group('indent')) # Divide source into lines; check that they're properly # indented; and then strip their indentation & prompts. source_lines = m.group('source').split('\n') self._check_prompt_blank(source_lines, indent, name, lineno) self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno) source = '\n'.join([sl[indent+4:] for sl in source_lines]) # Divide want into lines; check that it's properly indented; and # then strip the indentation. Spaces before the last newline should # be preserved, so plain rstrip() isn't good enough. want = m.group('want') want_lines = want.split('\n') if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): del want_lines[-1] # forget final newline & spaces after it self._check_prefix(want_lines, ' '*indent, name, lineno + len(source_lines)) want = '\n'.join([wl[indent:] for wl in want_lines]) # If `want` contains a traceback message, then extract it. m = self._EXCEPTION_RE.match(want) if m: exc_msg = m.group('msg') else: exc_msg = None # Extract options from the source. options = self._find_options(source, name, lineno) return source, options, want, exc_msg # This regular expression looks for option directives in the # source code of an example. Option directives are comments # starting with "doctest:". Warning: this may give false # positives for string-literals that contain the string # "#doctest:". Eliminating these false positives would require # actually parsing the string; but we limit them by ignoring any # line containing "#doctest:" that is *followed* by a quote mark. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$', re.MULTILINE) def _find_options(self, source, name, lineno): """ Return a dictionary containing option overrides extracted from option directives in the given source string. `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ options = {} # (note: with the current regexp, this will match at most once:) for m in self._OPTION_DIRECTIVE_RE.finditer(source): option_strings = m.group(1).replace(',', ' ').split() for option in option_strings: if (option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME): raise ValueError('line %r of the doctest for %s ' 'has an invalid option: %r' % (lineno+1, name, option)) flag = OPTIONFLAGS_BY_NAME[option[1:]] options[flag] = (option[0] == '+') if options and self._IS_BLANK_OR_COMMENT(source): raise ValueError('line %r of the doctest for %s has an option ' 'directive on a line with no example: %r' % (lineno, name, source)) return options # This regular expression finds the indentation of every non-blank # line in a string. _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE) def _min_indent(self, s): "Return the minimum indentation of any non-blank line in `s`" indents = [len(indent) for indent in self._INDENT_RE.findall(s)] if len(indents) > 0: return min(indents) else: return 0 def _check_prompt_blank(self, lines, indent, name, lineno): """ Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError. """ for i, line in enumerate(lines): if len(line) >= indent+4 and line[indent+3] != ' ': raise ValueError('line %r of the docstring for %s ' 'lacks blank after %s: %r' % (lineno+i+1, name, line[indent:indent+3], line)) def _check_prefix(self, lines, prefix, name, lineno): """ Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError. """ for i, line in enumerate(lines): if line and not line.startswith(prefix): raise ValueError('line %r of the docstring for %s has ' 'inconsistent leading whitespace: %r' % (lineno+i+1, name, line)) ###################################################################### ## 4. DocTest Finder ###################################################################### class DocTestFinder: """ A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. """ def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, _namefilter=None, exclude_empty=True): """ Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or objects that implement the same interface as DocTest). The signature for this factory function should match the signature of the DocTest constructor. If the optional argument `recurse` is false, then `find` will only examine the given object, and not any contained objects. If the optional argument `exclude_empty` is false, then `find` will include tests for objects with empty docstrings. """ self._parser = parser self._verbose = verbose self._recurse = recurse self._exclude_empty = exclude_empty # _namefilter is undocumented, and exists only for temporary backward- # compatibility support of testmod's deprecated isprivate mess. self._namefilter = _namefilter def find(self, obj, name=None, module=None, globs=None, extraglobs=None): """ Return a list of the DocTests that are defined by the given object's docstring, or by any of its contained objects' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. The object's module is used: - As a default namespace, if `globs` is not specified. - To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. - To find the name of the file containing the object. - To help find the line number of the object within its file. Contained objects whose module does not match `module` are ignored. If `module` is False, no attempt to find the module will be made. This is obscure, of use mostly in tests: if `module` is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests. The globals for each DocTest is formed by combining `globs` and `extraglobs` (bindings in `extraglobs` override bindings in `globs`). A new copy of the globals dictionary is created for each DocTest. If `globs` is not specified, then it defaults to the module's `__dict__`, if specified, or {} otherwise. If `extraglobs` is not specified, then it defaults to {}. """ # If name was not specified, then extract it from the object. if name is None: name = getattr(obj, '__name__', None) if name is None: raise ValueError("DocTestFinder.find: name must be given " "when obj.__name__ doesn't exist: %r" % (type(obj),)) # Find the module that contains the given object (if obj is # a module, then module=obj.). Note: this may fail, in which # case module will be None. if module is False: module = None elif module is None: module = inspect.getmodule(obj) # Read the module's source code. This is used by # DocTestFinder._find_lineno to find the line number for a # given object's docstring. try: file = inspect.getsourcefile(obj) or inspect.getfile(obj) source_lines = linecache.getlines(file) if not source_lines: source_lines = None except TypeError: source_lines = None # Initialize globals, and merge in extraglobs. if globs is None: if module is None: globs = {} else: globs = module.__dict__.copy() else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) # Recursively expore `obj`, extracting DocTests. tests = [] self._find(tests, obj, name, module, source_lines, globs, {}) return tests def _filter(self, obj, prefix, base): """ Return true if the given object should not be examined. """ return (self._namefilter is not None and self._namefilter(prefix, base)) def _from_module(self, module, object): """ Return true if the given object is defined in the given module. """ if module is None: return True elif inspect.isfunction(object): return module.__dict__ is object.func_globals elif inspect.isclass(object): return module.__name__ == object.__module__ elif isinstance(object, property): return True # [XX] no way not be sure. elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif hasattr(object, '__module__'): return module.__name__ == object.__module__ else: raise ValueError("object must be a class or function") def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to `tests`. """ if self._verbose: print 'Finding tests in %s' % name # If we've already processed this object, then ignore it. if id(obj) in seen: return seen[id(obj)] = 1 # Find a test for this object, and add it to the list of tests. test = self._get_test(obj, name, module, globs, source_lines) if test is not None: tests.append(test) # Look for tests in a module's contained objects. if inspect.ismodule(obj) and self._recurse: for valname, val in obj.__dict__.items(): # Check if this contained object should be ignored. if self._filter(val, name, valname): continue valname = '%s.%s' % (name, valname) # Recurse to functions & classes. if ((inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val)): self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a module's __test__ dictionary. if inspect.ismodule(obj) and self._recurse: for valname, val in getattr(obj, '__test__', {}).items(): if not isinstance(valname, basestring): raise ValueError("DocTestFinder.find: __test__ keys " "must be strings: %r" % (type(valname),)) if not (inspect.isfunction(val) or inspect.isclass(val) or inspect.ismethod(val) or inspect.ismodule(val) or isinstance(val, basestring)): raise ValueError("DocTestFinder.find: __test__ values " "must be strings, functions, methods, " "classes, or modules: %r" % (type(val),)) valname = '%s.__test__.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if inspect.isclass(obj) and self._recurse: for valname, val in obj.__dict__.items(): # Check if this contained object should be ignored. if self._filter(val, name, valname): continue # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).im_func # Recurse to methods, properties, and nested classes. if ((inspect.isfunction(val) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)): valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ # Extract the object's docstring. If it doesn't have one, # then return None (no test for this object). if isinstance(obj, basestring): docstring = obj else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, basestring): docstring = str(docstring) except (TypeError, AttributeError): docstring = '' # Find the docstring's location in the file. lineno = self._find_lineno(obj, source_lines) # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] return self._parser.get_doctest(docstring, globs, name, filename, lineno) def _find_lineno(self, obj, source_lines): """ Return a line number of the given object's docstring. Note: this method assumes that the object has a docstring. """ lineno = None # Find the line number for modules. if inspect.ismodule(obj): lineno = 0 # Find the line number for classes. # Note: this could be fooled if a class is defined multiple # times in a single file. if inspect.isclass(obj): if source_lines is None: return None pat = re.compile(r'^\s*class\s*%s\b' % getattr(obj, '__name__', '-')) for i, line in enumerate(source_lines): if pat.match(line): lineno = i break # Find the line number for functions & methods. if inspect.ismethod(obj): obj = obj.im_func if inspect.isfunction(obj): obj = obj.func_code if inspect.istraceback(obj): obj = obj.tb_frame if inspect.isframe(obj): obj = obj.f_code if inspect.iscode(obj): lineno = getattr(obj, 'co_firstlineno', None)-1 # Find the line number where the docstring starts. Assume # that it's the first line that begins with a quote mark. # Note: this could be fooled by a multiline function # signature, where a continuation line begins with a quote # mark. if lineno is not None: if source_lines is None: return lineno+1 pat = re.compile('(^|.*:)\s*\w*("|\')') for lineno in range(lineno, len(source_lines)): if pat.match(source_lines[lineno]): return lineno # We couldn't find the line number. return None ###################################################################### ## 5. DocTest Runner ###################################################################### class DocTestRunner: """ A class used to run DocTest test cases, and accumulate statistics. The `run` method is used to process a single DocTest case. It returns a tuple `(f, t)`, where `t` is the number of test cases tried, and `f` is the number of test cases that failed. >>> tests = DocTestFinder().find(_TestClass) >>> runner = DocTestRunner(verbose=False) >>> for test in tests: ... print runner.run(test) (0, 2) (0, 1) (0, 2) (0, 2) The `summarize` method prints a summary of all the test cases that have been run by the runner, and returns an aggregated `(f, t)` tuple: >>> runner.summarize(verbose=1) 4 items passed all tests: 2 tests in _TestClass 2 tests in _TestClass.__init__ 2 tests in _TestClass.get 1 tests in _TestClass.square 7 tests in 4 items. 7 passed and 0 failed. Test passed. (0, 7) The aggregated number of tried examples and failed examples is also available via the `tries` and `failures` attributes: >>> runner.tries 7 >>> runner.failures 0 The comparison between expected outputs and actual outputs is done by an `OutputChecker`. This comparison may be customized with a number of option flags; see the documentation for `testmod` for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of `OutputChecker` to the constructor. The test runner's display output can be controlled in two ways. First, an output function (`out) can be passed to `TestRunner.run`; this function will be called with strings that should be displayed. It defaults to `sys.stdout.write`. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods `report_start`, `report_success`, `report_unexpected_exception`, and `report_failure`. """ # This divider string is used to separate failure messages, and to # separate sections of the summary. DIVIDER = "*" * 70 def __init__(self, checker=None, verbose=None, optionflags=0): """ Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg 'verbose' prints lots of stuff if true, only failures if false; by default, it's true iff '-v' is in sys.argv. Optional argument `optionflags` can be used to control how the test runner compares expected output to actual output, and how it displays failures. See the documentation for `testmod` for more information. """ self._checker = checker or OutputChecker() if verbose is None: verbose = '-v' in sys.argv self._verbose = verbose self.optionflags = optionflags self.original_optionflags = optionflags # Keep track of the examples we've run. self.tries = 0 self.failures = 0 self._name2ft = {} # Create a fake output target for capturing doctest output. self._fakeout = _SpoofOut() #///////////////////////////////////////////////////////////////// # Reporting methods #///////////////////////////////////////////////////////////////// def report_start(self, out, test, example): """ Report that the test runner is about to process the given example. (Only displays a message if verbose=True) """ if self._verbose: if example.want: out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want)) else: out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n') def report_success(self, out, test, example, got): """ Report that the given example ran successfully. (Only displays a message if verbose=True) """ if self._verbose: out("ok\n") def report_failure(self, out, test, example, got): """ Report that the given example failed. """ out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)) def report_unexpected_exception(self, out, test, example, exc_info): """ Report that the given example raised an unexpected exception. """ out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info))) def _failure_header(self, test, example): out = [self.DIVIDER] if test.filename: if test.lineno is not None and example.lineno is not None: lineno = test.lineno + example.lineno + 1 else: lineno = '?' out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name)) else: out.append('Line %s, in %s' % (example.lineno+1, test.name)) out.append('Failed example:') source = example.source out.append(_indent(source)) return '\n'.join(out) #///////////////////////////////////////////////////////////////// # DocTest Running #///////////////////////////////////////////////////////////////// def __run(self, test, compileflags, out): """ Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the number of examples that failed. The examples are run in the namespace `test.globs`. """ # Keep track of the number of failures and tries. failures = tries = 0 # Save the option flags (since option directives can be used # to modify them). original_optionflags = self.optionflags SUCCESS, FAILURE, BOOM = range(3) # `outcome` state check = self._checker.check_output # Process each example. for examplenum, example in enumerate(test.examples): # If REPORT_ONLY_FIRST_FAILURE is set, then supress # reporting after the first failure. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and failures > 0) # Merge in the example's options. self.optionflags = original_optionflags if example.options: for (optionflag, val) in example.options.items(): if val: self.optionflags |= optionflag else: self.optionflags &= ~optionflag # Record that we started this example. tries += 1 if not quiet: self.report_start(out, test, example) # Use a special filename for compile(), so we can retrieve # the source code during interactive debugging (see # __patched_linecache_getlines). filename = '<doctest %s[%d]>' % (test.name, examplenum) # Run the example in the given context (globs), and record # any exception that gets raised. (But don't intercept # keyboard interrupts.) try: # Don't blink! This is where the user's code gets run. exec compile(example.source, filename, "single", compileflags, 1) in test.globs self.debugger.set_continue() # ==== Example Finished ==== exception = None except KeyboardInterrupt: raise except: exception = sys.exc_info() self.debugger.set_continue() # ==== Example Finished ==== got = self._fakeout.getvalue() # the actual output self._fakeout.truncate(0) outcome = FAILURE # guilty until proved innocent or insane # If the example executed without raising any exceptions, # verify its output. if exception is None: if check(example.want, got, self.optionflags): outcome = SUCCESS # The example raised an exception: check if it was expected. else: exc_info = sys.exc_info() exc_msg = traceback.format_exception_only(*exc_info[:2])[-1] if not quiet: got += _exception_traceback(exc_info) # If `example.exc_msg` is None, then we weren't expecting # an exception. if example.exc_msg is None: outcome = BOOM # We expected an exception: see whether it matches. elif check(example.exc_msg, exc_msg, self.optionflags): outcome = SUCCESS # Another chance if they didn't care about the detail. elif self.optionflags & IGNORE_EXCEPTION_DETAIL: m1 = re.match(r'[^:]*:', example.exc_msg) m2 = re.match(r'[^:]*:', exc_msg) if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags): outcome = SUCCESS # Report the outcome. if outcome is SUCCESS: if not quiet: self.report_success(out, test, example, got) elif outcome is FAILURE: if not quiet: self.report_failure(out, test, example, got) failures += 1 elif outcome is BOOM: if not quiet: self.report_unexpected_exception(out, test, example, exc_info) failures += 1 else: assert False, ("unknown outcome", outcome) # Restore the option flags (in case they were modified) self.optionflags = original_optionflags # Record and return the number of failures and tries. self.__record_outcome(test, failures, tries) return failures, tries def __record_outcome(self, test, f, t): """ Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples. """ f2, t2 = self._name2ft.get(test.name, (0,0)) self._name2ft[test.name] = (f+f2, t+t2) self.failures += f self.tries += t __LINECACHE_FILENAME_RE = re.compile(r'<doctest ' r'(?P<name>[\w\.]+)' r'\[(?P<examplenum>\d+)\]>$') def __patched_linecache_getlines(self, filename): m = self.__LINECACHE_FILENAME_RE.match(filename) if m and m.group('name') == self.test.name: example = self.test.examples[int(m.group('examplenum'))] return example.source.splitlines(True) else: return self.save_linecache_getlines(filename) def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use `clear_globs=False`. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. The output of each example is checked using `DocTestRunner.check_output`, and the results are formatted by the `DocTestRunner.report_*` methods. """ self.test = test if compileflags is None: compileflags = _extract_future_flags(test.globs) save_stdout = sys.stdout if out is None: out = save_stdout.write sys.stdout = self._fakeout # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). # Note that the interactive output will go to *our* # save_stdout, even if that's not the real sys.stdout; this # allows us to write test cases for the set_trace behavior. save_set_trace = pdb.set_trace self.debugger = _OutputRedirectingPdb(save_stdout) self.debugger.reset() pdb.set_trace = self.debugger.set_trace # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = linecache.getlines linecache.getlines = self.__patched_linecache_getlines try: return self.__run(test, compileflags, out) finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace linecache.getlines = self.save_linecache_getlines if clear_globs: test.globs.clear() #///////////////////////////////////////////////////////////////// # Summarization #///////////////////////////////////////////////////////////////// def summarize(self, verbose=None): """ Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner's verbosity is used. """ if verbose is None: verbose = self._verbose notests = [] passed = [] failed = [] totalt = totalf = 0 for x in self._name2ft.items(): name, (f, t) = x assert f <= t totalt += t totalf += f if t == 0: notests.append(name) elif f == 0: passed.append( (name, t) ) else: failed.append(x) if verbose: if notests: print len(notests), "items had no tests:" notests.sort() for thing in notests: print " ", thing if passed: print len(passed), "items passed all tests:" passed.sort() for thing, count in passed: print " %3d tests in %s" % (count, thing) if failed: print self.DIVIDER print len(failed), "items had failures:" failed.sort() for thing, (f, t) in failed: print " %3d of %3d in %s" % (f, t, thing) if verbose: print totalt, "tests in", len(self._name2ft), "items." print totalt - totalf, "passed and", totalf, "failed." if totalf: print "***Test Failed***", totalf, "failures." elif verbose: print "Test passed." return totalf, totalt #///////////////////////////////////////////////////////////////// # Backward compatibility cruft to maintain doctest.master. #///////////////////////////////////////////////////////////////// def merge(self, other): d = self._name2ft for name, (f, t) in other._name2ft.items(): if name in d: print "*** DocTestRunner.merge: '" + name + "' in both" \ " testers; summing outcomes." f2, t2 = d[name] f = f + f2 t = t + t2 d[name] = f, t class OutputChecker: """ A class used to check the whether the actual output from a doctest example matches the expected output. `OutputChecker` defines two methods: `check_output`, which compares a given pair of outputs, and returns true if they match; and `output_difference`, which returns a string describing the differences between two outputs. """ def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. """ # Handle the common case first, for efficiency: # if they're string-identical, always return true. if got == want: return True # The values True and False replaced 1 and 0 as the return # value for boolean comparisons in Python 2.3. if not (optionflags & DONT_ACCEPT_TRUE_FOR_1): if (got,want) == ("True\n", "1\n"): return True if (got,want) == ("False\n", "0\n"): return True # <BLANKLINE> can be used as a special sequence to signify a # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. if not (optionflags & DONT_ACCEPT_BLANKLINE): # Replace <BLANKLINE> in want with a blank line. want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER), '', want) # If a line in got contains only spaces, then remove the # spaces. got = re.sub('(?m)^\s*?$', '', got) if got == want: return True # This flag causes doctest to ignore any differences in the # contents of whitespace strings. Note that this can be used # in conjunction with the ELLIPSIS flag. if optionflags & NORMALIZE_WHITESPACE: got = ' '.join(got.split()) want = ' '.join(want.split()) if got == want: return True # The ELLIPSIS flag says to let the sequence "..." in `want` # match any substring in `got`. if optionflags & ELLIPSIS: if _ellipsis_match(want, got): return True # We didn't find any match; return false. return False # Should we do a fancy diff? def _do_a_fancy_diff(self, want, got, optionflags): # Not unless they asked for a fancy diff. if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF): return False # If expected output uses ellipsis, a meaningful fancy diff is # too hard ... or maybe not. In two real-life failures Tim saw, # a diff was a major help anyway, so this is commented out. # [todo] _ellipsis_match() knows which pieces do and don't match, # and could be the basis for a kick-ass diff in this case. ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want: ## return False # ndiff does intraline difference marking, so can be useful even # for 1-line differences. if optionflags & REPORT_NDIFF: return True # The other diff types need at least a few lines to be helpful. return want.count('\n') > 2 and got.count('\n') > 2 def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) # Check if we should use diff. if self._do_a_fancy_diff(want, got, optionflags): # Split want & got into lines. want_lines = want.splitlines(True) # True == keep line ends got_lines = got.splitlines(True) # Use difflib to find their differences. if optionflags & REPORT_UDIFF: diff = difflib.unified_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'unified diff with -expected +actual' elif optionflags & REPORT_CDIFF: diff = difflib.context_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'context diff with expected followed by actual' elif optionflags & REPORT_NDIFF: engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = list(engine.compare(want_lines, got_lines)) kind = 'ndiff with -expected +actual' else: assert 0, 'Bad diff option' # Remove trailing whitespace on diff output. diff = [line.rstrip() + '\n' for line in diff] return 'Differences (%s):\n' % kind + _indent(''.join(diff)) # If we're not using diff, then simply list the expected # output followed by the actual output. if want and got: return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)) elif want: return 'Expected:\n%sGot nothing\n' % _indent(want) elif got: return 'Expected nothing\nGot:\n%s' % _indent(got) else: return 'Expected nothing\nGot nothing\n' class DocTestFailure(Exception): """A DocTest example has failed in debugging mode. The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - got: the actual output """ def __init__(self, test, example, got): self.test = test self.example = example self.got = got def __str__(self): return str(self.test) class UnexpectedException(Exception): """A DocTest example has encountered an unexpected exception The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - exc_info: the exception info """ def __init__(self, test, example, exc_info): self.test = test self.example = example self.exc_info = exc_info def __str__(self): return str(self.test) class DebugRunner(DocTestRunner): r"""Run doc tests but raise an exception as soon as there is a failure. If an unexpected exception occurs, an UnexpectedException is raised. It contains the test, the example, and the original exception: >>> runner = DebugRunner(verbose=False) >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except UnexpectedException, failure: ... pass >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError We wrap the original exception to give the calling application access to the test and example information. If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' If a failure or error occurs, the globals are left intact: >>> del test.globs['__builtins__'] >>> test.globs {'x': 1} >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... >>> raise KeyError ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) Traceback (most recent call last): ... UnexpectedException: <DocTest foo from foo.py:0 (2 examples)> >>> del test.globs['__builtins__'] >>> test.globs {'x': 2} But the globals are cleared if there is no error: >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) (0, 1) >>> test.globs {} """ def run(self, test, compileflags=None, out=None, clear_globs=True): r = DocTestRunner.run(self, test, compileflags, out, False) if clear_globs: test.globs.clear() return r def report_unexpected_exception(self, out, test, example, exc_info): raise UnexpectedException(test, example, exc_info) def report_failure(self, out, test, example, got): raise DocTestFailure(test, example, got) ###################################################################### ## 6. Test Functions ###################################################################### # These should be backwards compatible. # For backward compatibility, a global instance of a DocTestRunner # class, updated by testmod. master = None def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False): """m=None, name=None, globs=None, verbose=None, isprivate=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False Test examples in docstrings in functions and classes reachable from module m (or the current module if m is not supplied), starting with m.__doc__. Unless isprivate is specified, private names are not skipped. Also test examples reachable from dict m.__test__ if it exists and is not None. m.__test__ maps names to functions, classes and strings; function and class docstrings are tested even if the name is private; strings are tested directly, as if they were docstrings. Return (#failures, #tests). See doctest.__doc__ for an overview. Optional keyword arg "name" gives the name of the module; by default use m.__name__. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use m.__dict__. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. This is new in 2.4. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. This is new in 2.3. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Deprecated in Python 2.4: Optional keyword arg "isprivate" specifies a function used to determine whether a name is private. The default function is treat all functions as public. Optionally, "isprivate" can be set to doctest.is_private to skip over functions marked as private using the underscore naming convention; see its docs for details. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if isprivate is not None: warnings.warn("the isprivate argument is deprecated; " "examine DocTestFinder.find() lists instead", DeprecationWarning) # If no module was given, then use __main__. if m is None: # DWA - m will still be None if this wasn't invoked from the command # line, in which case the following TypeError is about as good an error # as we should expect m = sys.modules.get('__main__') # Check that we were actually given a module. if not inspect.ismodule(m): raise TypeError("testmod: module required; %r" % (m,)) # If no name was given, then use the module's name. if name is None: name = m.__name__ # Find, parse, and run all tests in the given module. finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser()): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the test; by default use the file's basename. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg "parser" specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path if module_relative: package = _normalize_module(package) filename = _module_relative_path(package, filename) # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) # Read the file, convert it to a test, and run it. s = open(filename).read() test = parser.get_doctest(s, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries def run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0): """ Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is true, then generate output even if there are no failures. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. Optional keyword arg `optionflags` specifies options for the testing and output. See the documentation for `testmod` for more information. """ # Find, parse, and run all tests in the given module. finder = DocTestFinder(verbose=verbose, recurse=False) runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(f, name, globs=globs): runner.run(test, compileflags=compileflags) ###################################################################### ## 7. Tester ###################################################################### # This is provided only for backwards compatibility. It's not # actually used in any way. class Tester: def __init__(self, mod=None, globs=None, verbose=None, isprivate=None, optionflags=0): warnings.warn("class Tester is deprecated; " "use class doctest.DocTestRunner instead", DeprecationWarning, stacklevel=2) if mod is None and globs is None: raise TypeError("Tester.__init__: must specify mod or globs") if mod is not None and not inspect.ismodule(mod): raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,)) if globs is None: globs = mod.__dict__ self.globs = globs self.verbose = verbose self.isprivate = isprivate self.optionflags = optionflags self.testfinder = DocTestFinder(_namefilter=isprivate) self.testrunner = DocTestRunner(verbose=verbose, optionflags=optionflags) def runstring(self, s, name): test = DocTestParser().get_doctest(s, self.globs, name, None, None) if self.verbose: print "Running string", name (f,t) = self.testrunner.run(test) if self.verbose: print f, "of", t, "examples failed in string", name return (f,t) def rundoc(self, object, name=None, module=None): f = t = 0 tests = self.testfinder.find(object, name, module=module, globs=self.globs) for test in tests: (f2, t2) = self.testrunner.run(test) (f,t) = (f+f2, t+t2) return (f,t) def rundict(self, d, name, module=None): import new m = new.module(name) m.__dict__.update(d) if module is None: module = False return self.rundoc(m, name, module) def run__test__(self, d, name): import new m = new.module(name) m.__test__ = d return self.rundoc(m, name) def summarize(self, verbose=None): return self.testrunner.summarize(verbose) def merge(self, other): self.testrunner.merge(other.testrunner) ###################################################################### ## 8. Unittest Support ###################################################################### _unittest_reportflags = 0 def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> import doctest >>> old = doctest._unittest_reportflags >>> doctest.set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> doctest.set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old class DocTestCase(unittest.TestCase): def __init__(self, test, optionflags=0, setUp=None, tearDown=None, checker=None): unittest.TestCase.__init__(self) self._dt_optionflags = optionflags self._dt_checker = checker self._dt_test = test self._dt_setUp = setUp self._dt_tearDown = tearDown def setUp(self): test = self._dt_test if self._dt_setUp is not None: self._dt_setUp(test) def tearDown(self): test = self._dt_test if self._dt_tearDown is not None: self._dt_tearDown(test) test.globs.clear() def runTest(self): test = self._dt_test old = sys.stdout new = StringIO() optionflags = self._dt_optionflags if not (optionflags & REPORTING_FLAGS): # The option flags don't include any reporting flags, # so add the default reporting flags optionflags |= _unittest_reportflags runner = DocTestRunner(optionflags=optionflags, checker=self._dt_checker, verbose=False) try: runner.DIVIDER = "-"*70 failures, tries = runner.run( test, out=new.write, clear_globs=False) finally: sys.stdout = old if failures: raise self.failureException(self.format_failure(new.getvalue())) def format_failure(self, err): test = self._dt_test if test.lineno is None: lineno = 'unknown line number' else: lineno = '%s' % test.lineno lname = '.'.join(test.name.split('.')[-1:]) return ('Failed doctest test for %s\n' ' File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err) ) def debug(self): r"""Run the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. The DocTestCase provides a debug method that raises UnexpectedException errors if there is an unexepcted exception: >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except UnexpectedException, failure: ... pass The UnexpectedException contains the test, the example, and the original exception: >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' """ self.setUp() runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False) runner.run(self._dt_test) self.tearDown() def id(self): return self._dt_test.name def __repr__(self): name = self._dt_test.name.split('.') return "%s (%s)" % (name[-1], '.'.join(name[:-1])) __str__ = __repr__ def shortDescription(self): return "Doctest: " + self._dt_test.name def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ if test_finder is None: test_finder = DocTestFinder() module = _normalize_module(module) tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) if globs is None: globs = module.__dict__ if not tests: # Why do we want to do this? Because it reveals a bug that might # otherwise be hidden. raise ValueError(module, "has no tests") tests.sort() suite = unittest.TestSuite() for test in tests: if len(test.examples) == 0: continue if not test.filename: filename = module.__file__ if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] test.filename = filename suite.addTest(DocTestCase(test, **options)) return suite class DocFileCase(DocTestCase): def id(self): return '_'.join(self._dt_test.name.split('.')) def __repr__(self): return self._dt_test.filename __str__ = __repr__ def format_failure(self, err): return ('Failed doctest test for %s\n File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err) ) def DocFileTest(path, module_relative=True, package=None, globs=None, parser=DocTestParser(), **options): if globs is None: globs = {} if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path. if module_relative: package = _normalize_module(package) path = _module_relative_path(package, path) # Find the file and read it. name = os.path.basename(path) doc = open(path).read() # Convert it to a test, and wrap it in a DocFileCase. test = parser.get_doctest(doc, globs, name, path, 0) return DocFileCase(test, **options) def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. parser A DocTestParser (or subclass) that should be used to extract tests from the files. """ suite = unittest.TestSuite() # We do this here so that _normalize_module is called at the right # level. If it were called in DocFileTest, then this function # would be the caller and we might guess the package incorrectly. if kw.get('module_relative', True): kw['package'] = _normalize_module(kw.get('package')) for path in paths: suite.addTest(DocFileTest(path, **kw)) return suite ###################################################################### ## 9. Debugging Support ###################################################################### def script_from_examples(s): r"""Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum """ output = [] for piece in DocTestParser().parse(s): if isinstance(piece, Example): # Add the example's source code (strip trailing NL) output.append(piece.source[:-1]) # Add the expected output: want = piece.want if want: output.append('# Expected:') output += ['## '+l for l in want.split('\n')[:-1]] else: # Add non-example text. output += [_comment_line(l) for l in piece.split('\n')[:-1]] # Trim junk on both ends. while output and output[-1] == '#': output.pop() while output and output[0] == '#': output.pop(0) # Combine the output, and return it. return '\n'.join(output) def testsource(module, name): """Extract the test sources from a doctest docstring as a script. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the doc string with tests to be debugged. """ module = _normalize_module(module) tests = DocTestFinder().find(module) test = [t for t in tests if t.name == name] if not test: raise ValueError(name, "not found in tests") test = test[0] testsrc = script_from_examples(test.docstring) return testsrc def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" testsrc = script_from_examples(src) debug_script(testsrc, pm, globs) def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb # Note that tempfile.NameTemporaryFile() cannot be used. As the # docs say, a file so created cannot be opened by name a second time # on modern Windows boxes, and execfile() needs to open it. srcfilename = tempfile.mktemp(".py", "doctestdebug") f = open(srcfilename, 'w') f.write(src) f.close() try: if globs: globs = globs.copy() else: globs = {} if pm: try: execfile(srcfilename, globs, globs) except: print sys.exc_info()[1] pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause # backslashes to get treated as metacharacters on Windows. pdb.run("execfile(%r)" % srcfilename, globs, globs) finally: os.remove(srcfilename) def debug(module, name, pm=False): """Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. """ module = _normalize_module(module) testsrc = testsource(module, name) debug_script(testsrc, pm, module.__dict__) ###################################################################### ## 10. Example Usage ###################################################################### class _TestClass: """ A pointless class, for sanity-checking of docstring testing. Methods: square() get() >>> _TestClass(13).get() + _TestClass(-12).get() 1 >>> hex(_TestClass(13).square().get()) '0xa9' """ def __init__(self, val): """val -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print t.get() 123 """ self.val = val def square(self): """square() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 """ self.val = self.val ** 2 return self def get(self): """get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print x.get() -42 """ return self.val __test__ = {"_TestClass": _TestClass, "string": r""" Example of a string object, searched as-is. >>> x = 1; y = 2 >>> x + y, x * y (3, 2) """, "bool-int equivalence": r""" In 2.2, boolean expressions displayed 0 or 1. By default, we still accept them. This can be disabled by passing DONT_ACCEPT_TRUE_FOR_1 to the new optionflags argument. >>> 4 == 4 1 >>> 4 == 4 True >>> 4 > 4 0 >>> 4 > 4 False """, "blank lines": r""" Blank lines can be marked with <BLANKLINE>: >>> print 'foo\n\nbar\n' foo <BLANKLINE> bar <BLANKLINE> """, "ellipsis": r""" If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: >>> print range(1000) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] """, "whitespace normalization": r""" If the whitespace normalization flag is used, then differences in whitespace are ignored. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] """, } def _test(): r = unittest.TextTestRunner() r.run(DocTestSuite()) if __name__ == "__main__": _test()
Python
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG"] cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 'is not', 'exception match', 'BAD') hasconst = [] hasname = [] hasjrel = [] hasjabs = [] haslocal = [] hascompare = [] hasfree = [] opmap = {} opname = [''] * 256 for op in range(256): opname[op] = '<%r>' % (op,) del op def def_op(name, op): opname[op] = name opmap[name] = op def name_op(name, op): def_op(name, op) hasname.append(op) def jrel_op(name, op): def_op(name, op) hasjrel.append(op) def jabs_op(name, op): def_op(name, op) hasjabs.append(op) # Instruction opcodes for compiled code def_op('STOP_CODE', 0) def_op('POP_TOP', 1) def_op('ROT_TWO', 2) def_op('ROT_THREE', 3) def_op('DUP_TOP', 4) def_op('ROT_FOUR', 5) def_op('NOP', 9) def_op('UNARY_POSITIVE', 10) def_op('UNARY_NEGATIVE', 11) def_op('UNARY_NOT', 12) def_op('UNARY_CONVERT', 13) def_op('UNARY_INVERT', 15) def_op('LIST_APPEND', 18) def_op('BINARY_POWER', 19) def_op('BINARY_MULTIPLY', 20) def_op('BINARY_DIVIDE', 21) def_op('BINARY_MODULO', 22) def_op('BINARY_ADD', 23) def_op('BINARY_SUBTRACT', 24) def_op('BINARY_SUBSCR', 25) def_op('BINARY_FLOOR_DIVIDE', 26) def_op('BINARY_TRUE_DIVIDE', 27) def_op('INPLACE_FLOOR_DIVIDE', 28) def_op('INPLACE_TRUE_DIVIDE', 29) def_op('SLICE+0', 30) def_op('SLICE+1', 31) def_op('SLICE+2', 32) def_op('SLICE+3', 33) def_op('STORE_SLICE+0', 40) def_op('STORE_SLICE+1', 41) def_op('STORE_SLICE+2', 42) def_op('STORE_SLICE+3', 43) def_op('DELETE_SLICE+0', 50) def_op('DELETE_SLICE+1', 51) def_op('DELETE_SLICE+2', 52) def_op('DELETE_SLICE+3', 53) def_op('INPLACE_ADD', 55) def_op('INPLACE_SUBTRACT', 56) def_op('INPLACE_MULTIPLY', 57) def_op('INPLACE_DIVIDE', 58) def_op('INPLACE_MODULO', 59) def_op('STORE_SUBSCR', 60) def_op('DELETE_SUBSCR', 61) def_op('BINARY_LSHIFT', 62) def_op('BINARY_RSHIFT', 63) def_op('BINARY_AND', 64) def_op('BINARY_XOR', 65) def_op('BINARY_OR', 66) def_op('INPLACE_POWER', 67) def_op('GET_ITER', 68) def_op('PRINT_EXPR', 70) def_op('PRINT_ITEM', 71) def_op('PRINT_NEWLINE', 72) def_op('PRINT_ITEM_TO', 73) def_op('PRINT_NEWLINE_TO', 74) def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) def_op('INPLACE_XOR', 78) def_op('INPLACE_OR', 79) def_op('BREAK_LOOP', 80) def_op('WITH_CLEANUP', 81) def_op('LOAD_LOCALS', 82) def_op('RETURN_VALUE', 83) def_op('IMPORT_STAR', 84) def_op('EXEC_STMT', 85) def_op('YIELD_VALUE', 86) def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) def_op('BUILD_CLASS', 89) HAVE_ARGUMENT = 90 # Opcodes from here have an argument: name_op('STORE_NAME', 90) # Index in name list name_op('DELETE_NAME', 91) # "" def_op('UNPACK_SEQUENCE', 92) # Number of tuple items jrel_op('FOR_ITER', 93) name_op('STORE_ATTR', 95) # Index in name list name_op('DELETE_ATTR', 96) # "" name_op('STORE_GLOBAL', 97) # "" name_op('DELETE_GLOBAL', 98) # "" def_op('DUP_TOPX', 99) # number of items to duplicate def_op('LOAD_CONST', 100) # Index in const list hasconst.append(100) name_op('LOAD_NAME', 101) # Index in name list def_op('BUILD_TUPLE', 102) # Number of tuple items def_op('BUILD_LIST', 103) # Number of list items def_op('BUILD_MAP', 104) # Always zero for now name_op('LOAD_ATTR', 105) # Index in name list def_op('COMPARE_OP', 106) # Comparison operator hascompare.append(106) name_op('IMPORT_NAME', 107) # Index in name list name_op('IMPORT_FROM', 108) # Index in name list jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip jrel_op('JUMP_IF_FALSE', 111) # "" jrel_op('JUMP_IF_TRUE', 112) # "" jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code name_op('LOAD_GLOBAL', 116) # Index in name list jabs_op('CONTINUE_LOOP', 119) # Target address jrel_op('SETUP_LOOP', 120) # Distance to target address jrel_op('SETUP_EXCEPT', 121) # "" jrel_op('SETUP_FINALLY', 122) # "" def_op('LOAD_FAST', 124) # Local variable number haslocal.append(124) def_op('STORE_FAST', 125) # Local variable number haslocal.append(125) def_op('DELETE_FAST', 126) # Local variable number haslocal.append(126) def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3) def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8) def_op('MAKE_FUNCTION', 132) # Number of args with default values def_op('BUILD_SLICE', 133) # Number of items def_op('MAKE_CLOSURE', 134) def_op('LOAD_CLOSURE', 135) hasfree.append(135) def_op('LOAD_DEREF', 136) hasfree.append(136) def_op('STORE_DEREF', 137) hasfree.append(137) def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8) def_op('EXTENDED_ARG', 143) EXTENDED_ARG = 143 # pypy modification, experimental bytecode def_op('CALL_LIKELY_BUILTIN', 144) # #args + (#kwargs << 8) def_op('LOOKUP_METHOD', 145) # Index in name list def_op('CALL_METHOD', 146) # #args not including 'self' del def_op, name_op, jrel_op, jabs_op
Python
# Author: Fred L. Drake, Jr. # fdrake@acm.org # # This is a simple little module I wrote to make life easier. I didn't # see anything quite like it in the library, though I may have overlooked # something. I wrote this when I was trying to read some heavily nested # tuples with fairly non-descriptive content. This is modeled very much # after Lisp/Scheme - style pretty-printing of lists. If you find it # useful, thank small children who sleep at night. """Support to pretty-print lists, tuples, & dictionaries recursively. Very simple, but useful, especially in debugging data structures. Classes ------- PrettyPrinter() Handle pretty-printing operations onto a stream using a configured set of formatting parameters. Functions --------- pformat() Format a Python object into a pretty-printed representation. pprint() Pretty-print a Python object to a stream [default is sys.stdout]. saferepr() Generate a 'standard' repr()-like value, but protect against recursive data structures. """ import sys as _sys from cStringIO import StringIO as _StringIO __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", "PrettyPrinter"] # cache these for faster access: _commajoin = ", ".join _id = id _len = len _type = type def pprint(object, stream=None, indent=1, width=80, depth=None): """Pretty-print a Python object to a stream [default is sys.stdout].""" printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object) def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) def saferepr(object): """Version of repr() which can handle recursive data structures.""" return _safe_repr(object, {}, None, 0)[0] def isreadable(object): """Determine if saferepr(object) is readable by eval().""" return _safe_repr(object, {}, None, 0)[1] def isrecursive(object): """Determine if object requires a recursive representation.""" return _safe_repr(object, {}, None, 0)[2] class PrettyPrinter: def __init__(self, indent=1, width=80, depth=None, stream=None): """Handle pretty printing operations onto a stream using a set of configured parameters. indent Number of spaces to indent for each level of nesting. width Attempted maximum number of columns in the output. depth The maximum depth to print out nested structures. stream The desired output stream. If omitted (or false), the standard output stream available at construction will be used. """ indent = int(indent) width = int(width) assert indent >= 0, "indent must be >= 0" assert depth is None or depth > 0, "depth must be > 0" assert width, "width must be != 0" self._depth = depth self._indent_per_level = indent self._width = width if stream is not None: self._stream = stream else: self._stream = _sys.stdout def pprint(self, object): self._stream.write(self.pformat(object) + "\n") def pformat(self, object): sio = _StringIO() self._format(object, sio, 0, 0, {}, 0) return sio.getvalue() def isrecursive(self, object): return self.format(object, {}, 0, 0)[2] def isreadable(self, object): s, readable, recursive = self.format(object, {}, 0, 0) return readable and not recursive def _format(self, object, stream, indent, allowance, context, level): level = level + 1 objid = _id(object) if objid in context: stream.write(_recursion(object)) self._recursive = True self._readable = False return rep = self._repr(object, context, level - 1) typ = _type(object) sepLines = _len(rep) > (self._width - 1 - indent - allowance) write = stream.write if sepLines: r = getattr(typ, "__repr__", None) if issubclass(typ, dict) and r == dict.__repr__: write('{') if self._indent_per_level > 1: write((self._indent_per_level - 1) * ' ') length = _len(object) if length: context[objid] = 1 indent = indent + self._indent_per_level items = object.items() items.sort() key, ent = items[0] rep = self._repr(key, context, level) write(rep) write(': ') self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) if length > 1: for key, ent in items[1:]: rep = self._repr(key, context, level) write(',\n%s%s: ' % (' '*indent, rep)) self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) indent = indent - self._indent_per_level del context[objid] write('}') return if (issubclass(typ, list) and r == list.__repr__) or \ (issubclass(typ, tuple) and r == tuple.__repr__): if issubclass(typ, list): write('[') endchar = ']' else: write('(') endchar = ')' if self._indent_per_level > 1: write((self._indent_per_level - 1) * ' ') length = _len(object) if length: context[objid] = 1 indent = indent + self._indent_per_level self._format(object[0], stream, indent, allowance + 1, context, level) if length > 1: for ent in object[1:]: write(',\n' + ' '*indent) self._format(ent, stream, indent, allowance + 1, context, level) indent = indent - self._indent_per_level del context[objid] if issubclass(typ, tuple) and length == 1: write(',') write(endchar) return write(rep) def _repr(self, object, context, level): repr, readable, recursive = self.format(object, context.copy(), self._depth, level) if not readable: self._readable = False if recursive: self._recursive = True return repr def format(self, object, context, maxlevels, level): """Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct. """ return _safe_repr(object, context, maxlevels, level) # Return triple (repr_string, isreadable, isrecursive). def _safe_repr(object, context, maxlevels, level): typ = _type(object) if typ is str: if 'locale' not in _sys.modules: return repr(object), True, False if "'" in object and '"' not in object: closure = '"' quotes = {'"': '\\"'} else: closure = "'" quotes = {"'": "\\'"} qget = quotes.get sio = _StringIO() write = sio.write for char in object: if char.isalpha(): write(char) else: write(qget(char, repr(char)[1:-1])) return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False r = getattr(typ, "__repr__", None) if issubclass(typ, dict) and r == dict.__repr__: if not object: return "{}", True, False objid = _id(object) if maxlevels and level > maxlevels: return "{...}", False, objid in context if objid in context: return _recursion(object), False, True context[objid] = 1 readable = True recursive = False components = [] append = components.append level += 1 saferepr = _safe_repr for k, v in object.iteritems(): krepr, kreadable, krecur = saferepr(k, context, maxlevels, level) vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level) append("%s: %s" % (krepr, vrepr)) readable = readable and kreadable and vreadable if krecur or vrecur: recursive = True del context[objid] return "{%s}" % _commajoin(components), readable, recursive if (issubclass(typ, list) and r == list.__repr__) or \ (issubclass(typ, tuple) and r == tuple.__repr__): if issubclass(typ, list): if not object: return "[]", True, False format = "[%s]" elif _len(object) == 1: format = "(%s,)" else: if not object: return "()", True, False format = "(%s)" objid = _id(object) if maxlevels and level > maxlevels: return format % "...", False, objid in context if objid in context: return _recursion(object), False, True context[objid] = 1 readable = True recursive = False components = [] append = components.append level += 1 for o in object: orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) append(orepr) if not oreadable: readable = False if orecur: recursive = True del context[objid] return format % _commajoin(components), readable, recursive rep = repr(object) return rep, (rep and not rep.startswith('<')), False def _recursion(object): return ("<Recursion on %s with id=%s>" % (_type(object).__name__, _id(object))) def _perfcheck(object=None): import time if object is None: object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000 p = PrettyPrinter() t1 = time.time() _safe_repr(object, {}, None, 0) t2 = time.time() p.pformat(object) t3 = time.time() print "_safe_repr:", t2 - t1 print "pformat:", t3 - t2 if __name__ == "__main__": _perfcheck()
Python
"""Record of phased-in incompatible language changes. Each line is of the form: FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease "," CompilerFlag ")" where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples of the same form as sys.version_info: (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int PY_MINOR_VERSION, # the 1; an int PY_MICRO_VERSION, # the 0; an int PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string PY_RELEASE_SERIAL # the 3; an int ) OptionalRelease records the first release in which from __future__ import FeatureName was accepted. In the case of MandatoryReleases that have not yet occurred, MandatoryRelease predicts the release in which the feature will become part of the language. Else MandatoryRelease records when the feature became part of the language; in releases at or after that, modules no longer need from __future__ import FeatureName to use the feature in question, but may continue to use such imports. MandatoryRelease may also be None, meaning that a planned feature got dropped. Instances of class _Feature have two corresponding methods, .getOptionalRelease() and .getMandatoryRelease(). CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the builtin function compile() to enable the feature in dynamically compiled code. This flag is stored in the .compiler_flag attribute on _Future instances. These values must match the appropriate #defines of CO_xxx flags in Include/compile.h. No feature line is ever to be deleted from this file. """ all_feature_names = [ "nested_scopes", "generators", "division", "absolute_import", "with_statement", ] __all__ = ["all_feature_names"] + all_feature_names # The CO_xxx symbols are defined here under the same names used by # compile.h, so that an editor search will find them here. However, # they're not exported in __all__, because they don't really belong to # this module. CO_NESTED = 0x0010 # nested_scopes CO_GENERATOR_ALLOWED = 0 # generators (obsolete, was 0x1000) CO_FUTURE_DIVISION = 0x2000 # division CO_FUTURE_ABSIMPORT = 0x4000 # absolute_import CO_FUTURE_WITH_STATEMENT = 0x8000 # with statement class _Feature: def __init__(self, optionalRelease, mandatoryRelease, compiler_flag): self.optional = optionalRelease self.mandatory = mandatoryRelease self.compiler_flag = compiler_flag def getOptionalRelease(self): """Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info. """ return self.optional def getMandatoryRelease(self): """Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, is None. """ return self.mandatory def __repr__(self): return "_Feature" + repr((self.optional, self.mandatory, self.compiler_flag)) nested_scopes = _Feature((2, 1, 0, "beta", 1), (2, 2, 0, "alpha", 0), CO_NESTED) generators = _Feature((2, 2, 0, "alpha", 1), (2, 3, 0, "final", 0), CO_GENERATOR_ALLOWED) division = _Feature((2, 2, 0, "alpha", 2), (3, 0, 0, "alpha", 0), CO_FUTURE_DIVISION) absolute_import = _Feature((2, 5, 0, "alpha", 1), (2, 7, 0, "alpha", 0), CO_FUTURE_ABSIMPORT) with_statement = _Feature((2, 5, 0, "alpha", 1), (2, 6, 0, "alpha", 0), CO_FUTURE_WITH_STATEMENT)
Python
#! /usr/bin/env python # Copyright 1994 by Lance Ellinghouse # Cathedral City, California Republic, United States of America. # All Rights Reserved # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Lance Ellinghouse # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE # FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # Modified by Jack Jansen, CWI, July 1995: # - Use binascii module to do the actual line-by-line conversion # between ascii and binary. This results in a 1000-fold speedup. The C # version is still 5 times faster, though. # - Arguments more compliant with python standard """Implementation of the UUencode and UUdecode functions. encode(in_file, out_file [,name, mode]) decode(in_file [, out_file, mode]) """ import binascii import os import sys from types import StringType __all__ = ["Error", "encode", "decode"] class Error(Exception): pass def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n') def decode(in_file, out_file=None, mode=None, quiet=0): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr: raise Error, 'No valid begin line found in input file' if hdr[:5] != 'begin': continue hdrfields = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if os.path.exists(out_file): raise Error, 'Cannot overwrite existing file: %s' % out_file if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): fp = open(out_file, 'wb') try: os.chmod(out_file, mode) except AttributeError: pass out_file = fp # # Main decoding loop # s = in_file.readline() while s and s.strip() != 'end': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = binascii.a2b_uu(s[:nbytes]) if not quiet: sys.stderr.write("Warning: %s\n" % str(v)) out_file.write(data) s = in_file.readline() if not s: raise Error, 'Truncated input file' out_file.flush() try: fp.close() # If we create the file, don't leave the descriptor open except UnboundLocalError: pass def test(): """uuencode/uudecode main program""" import getopt dopt = 0 topt = 0 input = sys.stdin output = sys.stdout ok = 1 try: optlist, args = getopt.getopt(sys.argv[1:], 'dt') except getopt.error: ok = 0 if not ok or len(args) > 2: print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]' print ' -d: Decode (in stead of encode)' print ' -t: data is text, encoded format unix-compatible text' sys.exit(1) for o, a in optlist: if o == '-d': dopt = 1 if o == '-t': topt = 1 if len(args) > 0: input = args[0] if len(args) > 1: output = args[1] if dopt: if topt: if isinstance(output, StringType): output = open(output, 'w') else: print sys.argv[0], ': cannot do -t to stdout' sys.exit(1) decode(input, output) else: if topt: if isinstance(input, StringType): input = open(input, 'r') else: print sys.argv[0], ': cannot do -t from stdin' sys.exit(1) encode(input, output) if __name__ == '__main__': test()
Python
#! /usr/bin/env python # Copyright 1994 by Lance Ellinghouse # Cathedral City, California Republic, United States of America. # All Rights Reserved # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Lance Ellinghouse # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE # FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # Modified by Jack Jansen, CWI, July 1995: # - Use binascii module to do the actual line-by-line conversion # between ascii and binary. This results in a 1000-fold speedup. The C # version is still 5 times faster, though. # - Arguments more compliant with python standard """Implementation of the UUencode and UUdecode functions. encode(in_file, out_file [,name, mode]) decode(in_file [, out_file, mode]) """ import binascii import os import sys from types import StringType __all__ = ["Error", "encode", "decode"] class Error(Exception): pass def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n') def decode(in_file, out_file=None, mode=None, quiet=0): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr: raise Error, 'No valid begin line found in input file' if hdr[:5] != 'begin': continue hdrfields = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if os.path.exists(out_file): raise Error, 'Cannot overwrite existing file: %s' % out_file if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): fp = open(out_file, 'wb') try: os.chmod(out_file, mode) except AttributeError: pass out_file = fp # # Main decoding loop # s = in_file.readline() while s and s.strip() != 'end': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = binascii.a2b_uu(s[:nbytes]) if not quiet: sys.stderr.write("Warning: %s\n" % str(v)) out_file.write(data) s = in_file.readline() if not s: raise Error, 'Truncated input file' out_file.flush() try: fp.close() # If we create the file, don't leave the descriptor open except UnboundLocalError: pass def test(): """uuencode/uudecode main program""" import getopt dopt = 0 topt = 0 input = sys.stdin output = sys.stdout ok = 1 try: optlist, args = getopt.getopt(sys.argv[1:], 'dt') except getopt.error: ok = 0 if not ok or len(args) > 2: print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]' print ' -d: Decode (in stead of encode)' print ' -t: data is text, encoded format unix-compatible text' sys.exit(1) for o, a in optlist: if o == '-d': dopt = 1 if o == '-t': topt = 1 if len(args) > 0: input = args[0] if len(args) > 1: output = args[1] if dopt: if topt: if isinstance(output, StringType): output = open(output, 'w') else: print sys.argv[0], ': cannot do -t to stdout' sys.exit(1) decode(input, output) else: if topt: if isinstance(input, StringType): input = open(input, 'r') else: print sys.argv[0], ': cannot do -t from stdin' sys.exit(1) encode(input, output) if __name__ == '__main__': test()
Python
"""Append module search paths for third-party packages to sys.path. **************************************************************** * This module is automatically imported during initialization. * **************************************************************** In earlier versions of Python (up to 1.5a3), scripts or modules that needed to use site-specific modules would place ``import site'' somewhere near the top of their code. Because of the automatic import, this is no longer necessary (but code that does it still works). This will append site-specific paths to the module search path. On Unix, it starts with sys.prefix and sys.exec_prefix (if different) and appends lib/python<version>/site-packages as well as lib/site-python. On other platforms (mainly Mac and Windows), it uses just sys.prefix (and sys.exec_prefix, if different, but this is unlikely). The resulting directories, if they exist, are appended to sys.path, and also inspected for path configuration files. A path configuration file is a file whose name has the form <package>.pth; its contents are additional directories (one per line) to be added to sys.path. Non-existing directories (or non-directories) are never added to sys.path; no directory is added to sys.path more than once. Blank lines and lines beginning with '#' are skipped. Lines starting with 'import' are executed. For example, suppose sys.prefix and sys.exec_prefix are set to /usr/local and there is a directory /usr/local/lib/python1.5/site-packages with three subdirectories, foo, bar and spam, and two path configuration files, foo.pth and bar.pth. Assume foo.pth contains the following: # foo package configuration foo bar bletch and bar.pth contains: # bar package configuration bar Then the following directories are added to sys.path, in this order: /usr/local/lib/python1.5/site-packages/bar /usr/local/lib/python1.5/site-packages/foo Note that bletch is omitted because it doesn't exist; bar precedes foo because bar.pth comes alphabetically before foo.pth; and spam is omitted because it is not mentioned in either path configuration file. After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary additional site-specific customizations. If this import fails with an ImportError exception, it is silently ignored. """ import sys import os import __builtin__ def makepath(*paths): dir = os.path.abspath(os.path.join(*paths)) return dir, os.path.normcase(dir) def abs__file__(): """Set all module' __file__ attribute to an absolute path""" for m in sys.modules.values(): try: prev = m.__file__ new = os.path.abspath(m.__file__) if prev != new: m.__file__ = new except AttributeError: continue def removeduppaths(): """ Remove duplicate entries from sys.path along with making them absolute""" # This ensures that the initial path provided by the interpreter contains # only absolute pathnames, even if we're running from the build directory. L = [] known_paths = set() for dir in sys.path: # Filter out duplicate paths (on case-insensitive file systems also # if they only differ in case); turn relative paths into absolute # paths. dir, dircase = makepath(dir) if not dircase in known_paths: L.append(dir) known_paths.add(dircase) sys.path[:] = L return known_paths # XXX This should not be part of site.py, since it is needed even when # using the -S option for Python. See http://www.python.org/sf/586680 def addbuilddir(): """Append ./build/lib.<platform> in case we're running in the build dir (especially for Guido :-)""" from distutils.util import get_platform s = "build/lib.%s-%.3s" % (get_platform(), sys.version) s = os.path.join(os.path.dirname(sys.path[-1]), s) sys.path.append(s) def _init_pathinfo(): """Return a set containing all existing directory entries from sys.path""" d = set() for dir in sys.path: try: if os.path.isdir(dir): dir, dircase = makepath(dir) d.add(dircase) except TypeError: continue return d def addpackage(sitedir, name, known_paths): """Add a new path to known_paths by combining sitedir and 'name' or execute sitedir if it starts with 'import'""" if known_paths is None: _init_pathinfo() reset = 1 else: reset = 0 fullname = os.path.join(sitedir, name) try: f = open(fullname, "rU") except IOError: return try: for line in f: if line.startswith("#"): continue if line.startswith("import"): exec line continue line = line.rstrip() dir, dircase = makepath(sitedir, line) if not dircase in known_paths and os.path.exists(dir): sys.path.append(dir) known_paths.add(dircase) finally: f.close() if reset: known_paths = None return known_paths def addsitedir(sitedir, known_paths=None): """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir'""" if known_paths is None: known_paths = _init_pathinfo() reset = 1 else: reset = 0 sitedir, sitedircase = makepath(sitedir) if not sitedircase in known_paths: sys.path.append(sitedir) # Add path component try: names = os.listdir(sitedir) except os.error: return names.sort() for name in names: if name.endswith(os.extsep + "pth"): addpackage(sitedir, name, known_paths) if reset: known_paths = None return known_paths def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: if sys.platform in ('os2emx', 'riscos'): sitedirs = [os.path.join(prefix, "Lib", "site-packages")] elif os.sep == '/': sitedirs = [os.path.join(prefix, "lib", "python" + sys.version[:3], "site-packages"), os.path.join(prefix, "lib", "site-python")] else: sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")] if sys.platform == 'darwin': # for framework builds *only* we add the standard Apple # locations. Currently only per-user, but /Library and # /Network/Library could be added too if 'Python.framework' in prefix: home = os.environ.get('HOME') if home: sitedirs.append( os.path.join(home, 'Library', 'Python', sys.version[:3], 'site-packages')) for sitedir in sitedirs: if os.path.isdir(sitedir): addsitedir(sitedir, known_paths) return None def setBEGINLIBPATH(): """The OS/2 EMX port has optional extension modules that do double duty as DLLs (and must use the .DLL file extension) for other extensions. The library search path needs to be amended so these will be found during module import. Use BEGINLIBPATH so that these are at the start of the library search path. """ dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload") libpath = os.environ['BEGINLIBPATH'].split(';') if libpath[-1]: libpath.append(dllpath) else: libpath[-1] = dllpath os.environ['BEGINLIBPATH'] = ';'.join(libpath) def setquit(): """Define new built-ins 'quit' and 'exit'. These are simply strings that display a hint on how to exit. """ if os.sep == ':': exit = 'Use Cmd-Q to quit.' elif os.sep == '\\': exit = 'Use Ctrl-Z plus Return to exit.' else: exit = 'Use Ctrl-D (i.e. EOF) to exit.' __builtin__.quit = __builtin__.exit = exit class _Printer(object): """interactive prompt objects for printing the license text, a list of contributors and the copyright notice.""" MAXLINES = 23 def __init__(self, name, data, files=(), dirs=()): self.__name = name self.__data = data self.__files = files self.__dirs = dirs self.__lines = None def __setup(self): if self.__lines: return data = None for dir in self.__dirs: for filename in self.__files: filename = os.path.join(dir, filename) try: fp = file(filename, "rU") data = fp.read() fp.close() break except IOError: pass if data: break if not data: data = self.__data self.__lines = data.split('\n') self.__linecnt = len(self.__lines) def __repr__(self): self.__setup() if len(self.__lines) <= self.MAXLINES: return "\n".join(self.__lines) else: return "Type %s() to see the full %s text" % ((self.__name,)*2) def __call__(self): self.__setup() prompt = 'Hit Return for more, or q (and Return) to quit: ' lineno = 0 while 1: try: for i in range(lineno, lineno + self.MAXLINES): print self.__lines[i] except IndexError: break else: lineno += self.MAXLINES key = None while key is None: key = raw_input(prompt) if key not in ('', 'q'): key = None if key == 'q': break ##def setcopyright(): ## """Set 'copyright' and 'credits' in __builtin__""" ## __builtin__.copyright = _Printer("copyright", sys.copyright) ## if sys.platform[:4] == 'java': ## __builtin__.credits = _Printer( ## "credits", ## "Jython is maintained by the Jython developers (www.jython.org).") ## else: ## __builtin__.credits = _Printer("credits", """\ ## Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands ## for supporting Python development. See www.python.org for more information.""") ## here = os.path.dirname(os.__file__) ## __builtin__.license = _Printer( ## "license", "See http://www.python.org/%.3s/license.html" % sys.version, ## ["LICENSE.txt", "LICENSE"], ## [os.path.join(here, os.pardir), here, os.curdir]) def setcopyright(): # XXX this is the PyPy-specific version. Should be unified with the above. __builtin__.credits = _Printer( "credits", "PyPy is maintained by the PyPy developers: http://codespeak.net/pypy") __builtin__.license = _Printer( "license", "See http://codespeak.net/svn/pypy/dist/LICENSE") class _Helper(object): """Define the built-in 'help'. This is a wrapper around pydoc.help (with a twist). """ def __repr__(self): return "Type help() for interactive help, " \ "or help(object) for help about object." def __call__(self, *args, **kwds): import pydoc return pydoc.help(*args, **kwds) def sethelper(): __builtin__.help = _Helper() def aliasmbcs(): """On Windows, some default encodings are not provided by Python, while they are always available as "mbcs" in each locale. Make them usable by aliasing to "mbcs" in such a case.""" if sys.platform == 'win32': import locale, codecs enc = locale.getdefaultlocale()[1] if enc is not None and enc.startswith('cp'): # "cp***" ? try: codecs.lookup(enc) except LookupError: import encodings encodings._cache[enc] = encodings._unknown encodings.aliases.aliases[enc] = 'mbcs' def setencoding(): """Set the string encoding used by the Unicode implementation. The default is 'ascii', but if you're willing to experiment, you can change this.""" encoding = "ascii" # Default value set by _PyUnicode_Init() if 0: # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] if 0: # Enable to switch off string to Unicode coercion and implicit # Unicode to string conversion. encoding = "undefined" if encoding != "ascii": # On Non-Unicode builds this will raise an AttributeError... sys.setdefaultencoding(encoding) # Needs Python Unicode build ! def execsitecustomize(): """Run custom site specific code, if available.""" try: import sitecustomize except ImportError: pass def main(): abs__file__() paths_in_sys = removeduppaths() if (os.name == "posix" and sys.path and os.path.basename(sys.path[-1]) == "Modules"): addbuilddir() paths_in_sys = addsitepackages(paths_in_sys) if sys.platform == 'os2emx': setBEGINLIBPATH() setquit() setcopyright() sethelper() aliasmbcs() setencoding() execsitecustomize() # Remove sys.setdefaultencoding() so that users cannot change the # encoding after initialization. The test for presence is needed when # this module is run as a script, because this code is executed twice. if hasattr(sys, "setdefaultencoding"): del sys.setdefaultencoding main() def _test(): print "sys.path = [" for dir in sys.path: print " %r," % (dir,) print "]" if __name__ == '__main__': _test()
Python
"""Python part of the warnings subsystem.""" # Note: function level imports should *not* be used # in this module as it may cause import lock deadlock. # See bug 683658. import sys, types import linecache __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", "resetwarnings"] # filters contains a sequence of filter 5-tuples # The components of the 5-tuple are: # - an action: error, ignore, always, default, module, or once # - a compiled regex that must match the warning message # - a class representing the warning category # - a compiled regex that must match the module that is being warned # - a line number for the line being warning, or 0 to mean any line # If either if the compiled regexs are None, match anything. filters = [] defaultaction = "default" onceregistry = {} def warn(message, category=None, stacklevel=1): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning assert issubclass(category, Warning) # Get context information try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = "<string>" filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith(".pyc") or fnl.endswith(".pyo"): filename = filename[:-1] else: if module == "__main__": filename = sys.argv[0] if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry) def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} if isinstance(message, Warning): text = str(message) category = message.__class__ else: text = message message = category(message) key = (text, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if ((msg is None or msg.match(text)) and issubclass(category, cat) and (mod is None or mod.match(module)) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise message # Other actions if action == "once": registry[key] = 1 oncekey = (text, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (text, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%r) in warnings.filters:\n %s" % (action, item)) # Print message and context showwarning(message, category, filename, lineno) def showwarning(message, category, filename, lineno, file=None): """Hook to write a warning to a file; replace if you like.""" if file is None: file = sys.stderr try: file.write(formatwarning(message, category, filename, lineno)) except IOError: pass # the file (probably stderr) is invalid - this warning gets lost. def formatwarning(message, category, filename, lineno): """Function to format a warning the standard way.""" s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) line = linecache.getline(filename, lineno).strip() if line: s = s + " " + line + "\n" return s def filterwarnings(action, message="", category=Warning, module="", lineno=0, append=0): """Insert an entry into the list of warnings filters (at the front). Use assertions to check that all arguments have the right type.""" import re assert action in ("error", "ignore", "always", "default", "module", "once"), "invalid action: %r" % (action,) assert isinstance(message, basestring), "message must be a string" #assert isinstance(category, types.ClassType), "category must be a class" assert issubclass(category, Warning), "category must be a Warning subclass" assert isinstance(module, basestring), "module must be a string" assert isinstance(lineno, int) and lineno >= 0, \ "lineno must be an int >= 0" item = (action, re.compile(message, re.I), category, re.compile(module), lineno) if append: filters.append(item) else: filters.insert(0, item) def simplefilter(action, category=Warning, lineno=0, append=0): """Insert a simple entry into the list of warnings filters (at the front). A simple filter matches all modules and messages. """ assert action in ("error", "ignore", "always", "default", "module", "once"), "invalid action: %r" % (action,) assert isinstance(lineno, int) and lineno >= 0, \ "lineno must be an int >= 0" item = (action, None, category, None, lineno) if append: filters.append(item) else: filters.insert(0, item) def resetwarnings(): """Clear the list of warning filters, so that no filters are active.""" filters[:] = [] class _OptionError(Exception): """Exception used by option processing helpers.""" pass # Helper to process -W options passed via sys.warnoptions def _processoptions(args): for arg in args: try: _setoption(arg) except _OptionError, msg: print >>sys.stderr, "Invalid -W option ignored:", msg # Helper for _processoptions() def _setoption(arg): import re parts = arg.split(':') if len(parts) > 5: raise _OptionError("too many fields (max 5): %r" % (arg,)) while len(parts) < 5: parts.append('') action, message, category, module, lineno = [s.strip() for s in parts] action = _getaction(action) message = re.escape(message) category = _getcategory(category) module = re.escape(module) if module: module = module + '$' if lineno: try: lineno = int(lineno) if lineno < 0: raise ValueError except (ValueError, OverflowError): raise _OptionError("invalid lineno %r" % (lineno,)) else: lineno = 0 filterwarnings(action, message, category, module, lineno) # Helper for _setoption() def _getaction(action): if not action: return "default" if action == "all": return "always" # Alias for a in ['default', 'always', 'ignore', 'module', 'once', 'error']: if a.startswith(action): return a raise _OptionError("invalid action: %r" % (action,)) # Helper for _setoption() def _getcategory(category): import re if not category: return Warning if re.match("^[a-zA-Z0-9_]+$", category): try: cat = eval(category) except NameError: raise _OptionError("unknown warning category: %r" % (category,)) else: i = category.rfind(".") module = category[:i] klass = category[i+1:] try: m = __import__(module, None, None, [klass]) except ImportError: raise _OptionError("invalid module name: %r" % (module,)) try: cat = getattr(m, klass) except AttributeError: raise _OptionError("unknown warning category: %r" % (category,)) if not issubclass(cat, Warning): # or not isinstance(cat, types.ClassType): raise _OptionError("invalid warning category: %r" % (category,)) return cat # Module initialization _processoptions(sys.warnoptions) # XXX OverflowWarning should go away for Python 2.5. simplefilter("ignore", category=OverflowWarning, append=1) simplefilter("ignore", category=PendingDeprecationWarning, append=1)
Python
"""Create portable serialized representations of Python objects. See module cPickle for a (much) faster implementation. See module copy_reg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formats """ __version__ = "$Revision: 1.158 $" # Code version from types import * from copy_reg import dispatch_table from copy_reg import _extension_registry, _inverted_registry, _extension_cache import marshal import sys import struct import re import warnings __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler", "Unpickler", "dump", "dumps", "load", "loads"] # These are purely informational; no code uses these. format_version = "2.0" # File format version we write compatible_formats = ["1.0", # Original protocol 0 "1.1", # Protocol 0 with INST added "1.2", # Original protocol 1 "1.3", # Protocol 1 with BINFLOAT added "2.0", # Protocol 2 ] # Old format versions we can read # Keep in synch with cPickle. This is the highest protocol number we # know how to read. HIGHEST_PROTOCOL = 2 # Why use struct.pack() for pickling but marshal.loads() for # unpickling? struct.pack() is 40% faster than marshal.dumps(), but # marshal.loads() is twice as fast as struct.unpack()! mloads = marshal.loads class PickleError(Exception): """A common base class for the other pickling exceptions.""" pass class PicklingError(PickleError): """This exception is raised when an unpicklable object is passed to the dump() method. """ pass class UnpicklingError(PickleError): """This exception is raised when there is a problem unpickling an object, such as a security violation. Note that other exceptions may also be raised during unpickling, including (but not necessarily limited to) AttributeError, EOFError, ImportError, and IndexError. """ pass # An instance of _Stop is raised by Unpickler.load_stop() in response to # the STOP opcode, passing the object that is the result of unpickling. class _Stop(Exception): def __init__(self, value): self.value = value # Jython has PyStringMap; it's a dict subclass with string keys try: from org.python.core import PyStringMap except ImportError: PyStringMap = None # UnicodeType may or may not be exported (normally imported from types) try: UnicodeType except NameError: UnicodeType = None # Pickle opcodes. See pickletools.py for extensive docs. The listing # here is in kind-of alphabetical order of 1-character pickle code. # pickletools groups them by purpose. MARK = '(' # push special markobject on stack STOP = '.' # every pickle ends with STOP POP = '0' # discard topmost stack item POP_MARK = '1' # discard stack top through topmost markobject DUP = '2' # duplicate top stack item FLOAT = 'F' # push float object; decimal string argument INT = 'I' # push integer or bool; decimal string argument BININT = 'J' # push four-byte signed int BININT1 = 'K' # push 1-byte unsigned int LONG = 'L' # push long; decimal string argument BININT2 = 'M' # push 2-byte unsigned int NONE = 'N' # push None PERSID = 'P' # push persistent object; id is taken from string arg BINPERSID = 'Q' # " " " ; " " " " stack REDUCE = 'R' # apply callable to argtuple, both on stack STRING = 'S' # push string; NL-terminated string argument BINSTRING = 'T' # push string; counted binary string argument SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument BINUNICODE = 'X' # " " " ; counted UTF-8 string argument APPEND = 'a' # append stack top to list below it BUILD = 'b' # call __setstate__ or __dict__.update() GLOBAL = 'c' # push self.find_class(modname, name); 2 string args DICT = 'd' # build a dict from stack items EMPTY_DICT = '}' # push empty dict APPENDS = 'e' # extend list on stack by topmost stack slice GET = 'g' # push item from memo on stack; index is string arg BINGET = 'h' # " " " " " " ; " " 1-byte arg INST = 'i' # build & push class instance LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg LIST = 'l' # build list from topmost stack items EMPTY_LIST = ']' # push empty list OBJ = 'o' # build & push class instance PUT = 'p' # store stack top in memo; index is string arg BINPUT = 'q' # " " " " " ; " " 1-byte arg LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg SETITEM = 's' # add key+value pair to dict TUPLE = 't' # build tuple from topmost stack items EMPTY_TUPLE = ')' # push empty tuple SETITEMS = 'u' # modify dict by adding topmost key+value pairs BINFLOAT = 'G' # push float; arg is 8-byte float encoding TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py # Protocol 2 PROTO = '\x80' # identify pickle protocol NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple EXT1 = '\x82' # push object from extension registry; 1-byte index EXT2 = '\x83' # ditto, but 2-byte index EXT4 = '\x84' # ditto, but 4-byte index TUPLE1 = '\x85' # build 1-tuple from stack top TUPLE2 = '\x86' # build 2-tuple from two topmost stack items TUPLE3 = '\x87' # build 3-tuple from three topmost stack items NEWTRUE = '\x88' # push True NEWFALSE = '\x89' # push False LONG1 = '\x8a' # push long from < 256 bytes LONG4 = '\x8b' # push really big long _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3] __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)]) del x # Pickling machinery class Pickler: def __init__(self, file, protocol=None, bin=None): """This takes a file-like object for writing a pickle data stream. The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text mode and read back successfully. When using a protocol higher than 0, make sure the file is opened in binary mode, both when pickling and unpickling.) Protocol 1 is more efficient than protocol 0; protocol 2 is more efficient than protocol 1. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The file parameter must have a write() method that accepts a single string argument. It can thus be an open file object, a StringIO object, or any other custom object that meets this interface. """ if protocol is not None and bin is not None: raise ValueError, "can't specify both 'protocol' and 'bin'" if bin is not None: warnings.warn("The 'bin' argument to Pickler() is deprecated", DeprecationWarning) protocol = bin if protocol is None: protocol = 0 if protocol < 0: protocol = HIGHEST_PROTOCOL elif not 0 <= protocol <= HIGHEST_PROTOCOL: raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) self.write = file.write self.memo = {} self.proto = int(protocol) self.bin = protocol >= 1 self.fast = 0 def _pickle_moduledict(self, obj): try: modict = self.module_dict_ids except AttributeError: modict = {} from sys import modules for mod in modules.values(): if isinstance(mod, ModuleType): try: modict[id(mod.__dict__)] = mod except KeyboardInterrupt: raise except: # obscure: the above can fail for # arbitrary reasons, because of the py lib pass self.module_dict_ids = modict thisid = id(obj) try: themodule = modict[thisid] except KeyError: return None from __builtin__ import getattr return getattr, (themodule, '__dict__') def clear_memo(self): """Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are pickled by reference and not by value. This method is useful when re-using picklers. """ self.memo.clear() def dump(self, obj): """Write a pickled representation of obj to the open file.""" if self.proto >= 2: self.write(PROTO + chr(self.proto)) self.save(obj) self.write(STOP) def memoize(self, obj): """Store an object in the memo.""" # The Pickler memo is a dictionary mapping object ids to 2-tuples # that contain the Unpickler memo key and the object being memoized. # The memo key is written to the pickle and will become # the key in the Unpickler's memo. The object is stored in the # Pickler memo so that transient objects are kept alive during # pickling. # The use of the Unpickler memo length as the memo key is just a # convention. The only requirement is that the memo values be unique. # But there appears no advantage to any other scheme, and this # scheme allows the Unpickler memo to be implemented as a plain (but # growable) array, indexed by memo key. if self.fast: return assert id(obj) not in self.memo memo_len = len(self.memo) self.write(self.put(memo_len)) self.memo[id(obj)] = memo_len, obj # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i. def put(self, i, pack=struct.pack): if self.bin: if i < 256: return BINPUT + chr(i) else: return LONG_BINPUT + pack("<i", i) return PUT + repr(i) + '\n' # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i. def get(self, i, pack=struct.pack): if self.bin: if i < 256: return BINGET + chr(i) else: return LONG_BINGET + pack("<i", i) return GET + repr(i) + '\n' def save(self, obj): # Check for persistent id (defined by a subclass) pid = self.persistent_id(obj) if pid: self.save_pers(pid) return # Check the memo x = self.memo.get(id(obj)) if x: self.write(self.get(x[0])) return # Check the type dispatch table t = type(obj) f = self.dispatch.get(t) if f: f(self, obj) # Call unbound method with explicit self return # Check for a class with a custom metaclass; treat as regular class try: issc = issubclass(t, TypeType) except TypeError: # t is not a class (old Boost; see SF #502085) issc = 0 if issc: self.save_global(obj) return # Check copy_reg.dispatch_table reduce = dispatch_table.get(t) if reduce: rv = reduce(obj) else: # Check for a __reduce_ex__ method, fall back to __reduce__ reduce = getattr(obj, "__reduce_ex__", None) if reduce: rv = reduce(self.proto) else: reduce = getattr(obj, "__reduce__", None) if reduce: rv = reduce() else: raise PicklingError("Can't pickle %r object: %r" % (t.__name__, obj)) # Check for string returned by reduce(), meaning "save as global" if type(rv) is StringType: self.save_global(obj, rv) return # Assert that reduce() returned a tuple if type(rv) is not TupleType: raise PicklingError("%s must return string or tuple" % reduce) # Assert that it returned an appropriately sized tuple l = len(rv) if not (2 <= l <= 5): raise PicklingError("Tuple returned by %s must have " "two to five elements" % reduce) # Save the reduce() output and finally memoize the object self.save_reduce(obj=obj, *rv) def persistent_id(self, obj): # This exists so a subclass can override it return None def save_pers(self, pid): # Save a persistent id reference if self.bin: self.save(pid) self.write(BINPERSID) else: self.write(PERSID + str(pid) + '\n') def save_reduce(self, func, args, state=None, listitems=None, dictitems=None, obj=None): # This API is called by some subclasses # Assert that args is a tuple or None if not isinstance(args, TupleType): if args is None: # A hack for Jim Fulton's ExtensionClass, now deprecated. # See load_reduce() warnings.warn("__basicnew__ special case is deprecated", DeprecationWarning) else: raise PicklingError( "args from reduce() should be a tuple") # Assert that func is callable if not callable(func): raise PicklingError("func from reduce should be callable") save = self.save write = self.write # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__": # A __reduce__ implementation can direct protocol 2 to # use the more efficient NEWOBJ opcode, while still # allowing protocol 0 and 1 to work normally. For this to # work, the function returned by __reduce__ should be # called __newobj__, and its first argument should be a # new-style class. The implementation for __newobj__ # should be as follows, although pickle has no way to # verify this: # # def __newobj__(cls, *args): # return cls.__new__(cls, *args) # # Protocols 0 and 1 will pickle a reference to __newobj__, # while protocol 2 (and above) will pickle a reference to # cls, the remaining args tuple, and the NEWOBJ code, # which calls cls.__new__(cls, *args) at unpickling time # (see load_newobj below). If __reduce__ returns a # three-tuple, the state from the third tuple item will be # pickled regardless of the protocol, calling __setstate__ # at unpickling time (see load_build below). # # Note that no standard __newobj__ implementation exists; # you have to provide your own. This is to enforce # compatibility with Python 2.2 (pickles written using # protocol 0 or 1 in Python 2.3 should be unpicklable by # Python 2.2). cls = args[0] if not hasattr(cls, "__new__"): raise PicklingError( "args[0] from __newobj__ args has no __new__") if obj is not None and cls is not obj.__class__: raise PicklingError( "args[0] from __newobj__ args has the wrong class") args = args[1:] save(cls) save(args) write(NEWOBJ) else: save(func) save(args) write(REDUCE) if obj is not None: self.memoize(obj) # More new special cases (that work with older protocols as # well): when __reduce__ returns a tuple with 4 or 5 items, # the 4th and 5th item should be iterators that provide list # items and dict items (as (key, value) tuples), or None. if listitems is not None: self._batch_appends(listitems) if dictitems is not None: self._batch_setitems(dictitems) if state is not None: save(state) write(BUILD) # Methods below this point are dispatched through the dispatch table dispatch = {} def save_none(self, obj): self.write(NONE) dispatch[NoneType] = save_none def save_bool(self, obj): if self.proto >= 2: self.write(obj and NEWTRUE or NEWFALSE) else: self.write(obj and TRUE or FALSE) dispatch[bool] = save_bool def save_int(self, obj, pack=struct.pack): if self.bin: # If the int is small enough to fit in a signed 4-byte 2's-comp # format, we can store it more efficiently than the general # case. # First one- and two-byte unsigned ints: if obj >= 0: if obj <= 0xff: self.write(BININT1 + chr(obj)) return if obj <= 0xffff: self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8)) return # Next check for 4-byte signed ints: high_bits = obj >> 31 # note that Python shift sign-extends if high_bits == 0 or high_bits == -1: # All high bits are copies of bit 2**31, so the value # fits in a 4-byte signed int. self.write(BININT + pack("<i", obj)) return # Text pickle, or int too big to fit in signed 4-byte format. self.write(INT + repr(obj) + '\n') dispatch[IntType] = save_int def save_long(self, obj, pack=struct.pack): if self.proto >= 2: bytes = encode_long(obj) n = len(bytes) if n < 256: self.write(LONG1 + chr(n) + bytes) else: self.write(LONG4 + pack("<i", n) + bytes) return self.write(LONG + repr(obj) + '\n') dispatch[LongType] = save_long def save_float(self, obj, pack=struct.pack): if self.bin: self.write(BINFLOAT + pack('>d', obj)) else: self.write(FLOAT + repr(obj) + '\n') dispatch[FloatType] = save_float def save_string(self, obj, pack=struct.pack): if self.bin: n = len(obj) if n < 256: self.write(SHORT_BINSTRING + chr(n) + obj) else: self.write(BINSTRING + pack("<i", n) + obj) else: self.write(STRING + repr(obj) + '\n') self.memoize(obj) dispatch[StringType] = save_string def save_unicode(self, obj, pack=struct.pack): if self.bin: encoding = obj.encode('utf-8') n = len(encoding) self.write(BINUNICODE + pack("<i", n) + encoding) else: obj = obj.replace("\\", "\\u005c") obj = obj.replace("\n", "\\u000a") self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n') self.memoize(obj) dispatch[UnicodeType] = save_unicode if StringType == UnicodeType: # This is true for Jython def save_string(self, obj, pack=struct.pack): unicode = obj.isunicode() if self.bin: if unicode: obj = obj.encode("utf-8") l = len(obj) if l < 256 and not unicode: self.write(SHORT_BINSTRING + chr(l) + obj) else: s = pack("<i", l) if unicode: self.write(BINUNICODE + s + obj) else: self.write(BINSTRING + s + obj) else: if unicode: obj = obj.replace("\\", "\\u005c") obj = obj.replace("\n", "\\u000a") obj = obj.encode('raw-unicode-escape') self.write(UNICODE + obj + '\n') else: self.write(STRING + repr(obj) + '\n') self.memoize(obj) dispatch[StringType] = save_string def save_tuple(self, obj): write = self.write proto = self.proto n = len(obj) if n == 0: if proto: write(EMPTY_TUPLE) else: write(MARK + TUPLE) return save = self.save memo = self.memo if n <= 3 and proto >= 2: for element in obj: save(element) # Subtle. Same as in the big comment below. if id(obj) in memo: get = self.get(memo[id(obj)][0]) write(POP * n + get) else: write(_tuplesize2code[n]) self.memoize(obj) return # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple # has more than 3 elements. write(MARK) for element in obj: save(element) if id(obj) in memo: # Subtle. d was not in memo when we entered save_tuple(), so # the process of saving the tuple's elements must have saved # the tuple itself: the tuple is recursive. The proper action # now is to throw away everything we put on the stack, and # simply GET the tuple (it's already constructed). This check # could have been done in the "for element" loop instead, but # recursive tuples are a rare thing. get = self.get(memo[id(obj)][0]) if proto: write(POP_MARK + get) else: # proto 0 -- POP_MARK not available write(POP * (n+1) + get) return # No recursion. self.write(TUPLE) self.memoize(obj) dispatch[TupleType] = save_tuple # save_empty_tuple() isn't used by anything in Python 2.3. However, I # found a Pickler subclass in Zope3 that calls it, so it's not harmless # to remove it. def save_empty_tuple(self, obj): self.write(EMPTY_TUPLE) def save_list(self, obj): write = self.write if self.bin: write(EMPTY_LIST) else: # proto 0 -- can't use EMPTY_LIST write(MARK + LIST) self.memoize(obj) self._batch_appends(iter(obj)) dispatch[ListType] = save_list # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets # out of synch, though. _BATCHSIZE = 1000 def _batch_appends(self, items): # Helper to batch up APPENDS sequences save = self.save write = self.write if not self.bin: for x in items: save(x) write(APPEND) return r = xrange(self._BATCHSIZE) while items is not None: tmp = [] for i in r: try: x = items.next() tmp.append(x) except StopIteration: items = None break n = len(tmp) if n > 1: write(MARK) for x in tmp: save(x) write(APPENDS) elif n: save(tmp[0]) write(APPEND) # else tmp is empty, and we're done def save_dict(self, obj): ## Stackless addition BEGIN modict_saver = self._pickle_moduledict(obj) if modict_saver is not None: return self.save_reduce(*modict_saver) ## Stackless addition END write = self.write if self.bin: write(EMPTY_DICT) else: # proto 0 -- can't use EMPTY_DICT write(MARK + DICT) self.memoize(obj) self._batch_setitems(obj.iteritems()) dispatch[DictionaryType] = save_dict if not PyStringMap is None: dispatch[PyStringMap] = save_dict def _batch_setitems(self, items): # Helper to batch up SETITEMS sequences; proto >= 1 only save = self.save write = self.write if not self.bin: for k, v in items: save(k) save(v) write(SETITEM) return r = xrange(self._BATCHSIZE) while items is not None: tmp = [] for i in r: try: tmp.append(items.next()) except StopIteration: items = None break n = len(tmp) if n > 1: write(MARK) for k, v in tmp: save(k) save(v) write(SETITEMS) elif n: k, v = tmp[0] save(k) save(v) write(SETITEM) # else tmp is empty, and we're done def save_inst(self, obj): cls = obj.__class__ memo = self.memo write = self.write save = self.save if hasattr(obj, '__getinitargs__'): args = obj.__getinitargs__() len(args) # XXX Assert it's a sequence _keep_alive(args, memo) else: args = () write(MARK) if self.bin: save(cls) for arg in args: save(arg) write(OBJ) else: for arg in args: save(arg) write(INST + cls.__module__ + '\n' + cls.__name__ + '\n') self.memoize(obj) try: getstate = obj.__getstate__ except AttributeError: stuff = obj.__dict__ else: stuff = getstate() _keep_alive(stuff, memo) save(stuff) write(BUILD) dispatch[InstanceType] = save_inst def save_global(self, obj, name=None, pack=struct.pack): write = self.write memo = self.memo if name is None: name = obj.__name__ module = getattr(obj, "__module__", None) if module is None: module = whichmodule(obj, name) try: __import__(module) mod = sys.modules[module] klass = getattr(mod, name) except (ImportError, KeyError, AttributeError): raise PicklingError( "Can't pickle %r: it's not found as %s.%s" % (obj, module, name)) else: if klass is not obj: raise PicklingError( "Can't pickle %r: it's not the same object as %s.%s" % (obj, module, name)) if self.proto >= 2: code = _extension_registry.get((module, name)) if code: assert code > 0 if code <= 0xff: write(EXT1 + chr(code)) elif code <= 0xffff: write("%c%c%c" % (EXT2, code&0xff, code>>8)) else: write(EXT4 + pack("<i", code)) return write(GLOBAL + module + '\n' + name + '\n') self.memoize(obj) def save_function(self, obj): try: return self.save_global(obj) except PicklingError, e: pass # Check copy_reg.dispatch_table reduce = dispatch_table.get(type(obj)) if reduce: rv = reduce(obj) else: # Check for a __reduce_ex__ method, fall back to __reduce__ reduce = getattr(obj, "__reduce_ex__", None) if reduce: rv = reduce(self.proto) else: reduce = getattr(obj, "__reduce__", None) if reduce: rv = reduce() else: raise e return self.save_reduce(obj=obj, *rv) dispatch[ClassType] = save_global dispatch[FunctionType] = save_function dispatch[BuiltinFunctionType] = save_global dispatch[TypeType] = save_global # Pickling helpers def _keep_alive(x, memo): """Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo itself... """ try: memo[id(memo)].append(x) except KeyError: # aha, this is the first one :-) memo[id(memo)]=[x] # A cache for whichmodule(), mapping a function object to the name of # the module in which the function was found. classmap = {} # called classmap for backwards compatibility def whichmodule(func, funcname): """Figure out the module in which a function occurs. Search sys.modules for the module. Cache in classmap. Return a module name. If the function cannot be found, return "__main__". """ # Python functions should always get an __module__ from their globals. mod = getattr(func, "__module__", None) if mod is not None: return mod if func in classmap: return classmap[func] for name, module in sys.modules.items(): if module is None: continue # skip dummy package entries if name != '__main__' and getattr(module, funcname, None) is func: break else: name = '__main__' classmap[func] = name return name # Unpickling machinery class Unpickler: def __init__(self, file): """This takes a file-like object for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. The file-like object must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return a string. Thus file-like object can be a file object opened for reading, a StringIO object, or any other custom object that meets this interface. """ self.readline = file.readline self.read = file.read self.memo = {} def load(self): """Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file. """ self.mark = object() # any new unique object self.stack = [] self.append = self.stack.append read = self.read dispatch = self.dispatch try: while 1: key = read(1) dispatch[key](self) except _Stop, stopinst: return stopinst.value # Return largest index k such that self.stack[k] is self.mark. # If the stack doesn't contain a mark, eventually raises IndexError. # This could be sped by maintaining another stack, of indices at which # the mark appears. For that matter, the latter stack would suffice, # and we wouldn't need to push mark objects on self.stack at all. # Doing so is probably a good thing, though, since if the pickle is # corrupt (or hostile) we may get a clue from finding self.mark embedded # in unpickled objects. def marker(self): stack = self.stack mark = self.mark k = len(stack)-1 while stack[k] is not mark: k = k-1 return k dispatch = {} def load_eof(self): raise EOFError dispatch[''] = load_eof def load_proto(self): proto = ord(self.read(1)) if not 0 <= proto <= 2: raise ValueError, "unsupported pickle protocol: %d" % proto dispatch[PROTO] = load_proto def load_persid(self): pid = self.readline()[:-1] self.append(self.persistent_load(pid)) dispatch[PERSID] = load_persid def load_binpersid(self): pid = self.stack.pop() self.append(self.persistent_load(pid)) dispatch[BINPERSID] = load_binpersid def load_none(self): self.append(None) dispatch[NONE] = load_none def load_false(self): self.append(False) dispatch[NEWFALSE] = load_false def load_true(self): self.append(True) dispatch[NEWTRUE] = load_true def load_int(self): data = self.readline() if data == FALSE[1:]: val = False elif data == TRUE[1:]: val = True else: try: val = int(data) except ValueError: val = long(data) self.append(val) dispatch[INT] = load_int def load_binint(self): self.append(mloads('i' + self.read(4))) dispatch[BININT] = load_binint def load_binint1(self): self.append(ord(self.read(1))) dispatch[BININT1] = load_binint1 def load_binint2(self): self.append(mloads('i' + self.read(2) + '\000\000')) dispatch[BININT2] = load_binint2 def load_long(self): self.append(long(self.readline()[:-1], 0)) dispatch[LONG] = load_long def load_long1(self): n = ord(self.read(1)) bytes = self.read(n) self.append(decode_long(bytes)) dispatch[LONG1] = load_long1 def load_long4(self): n = mloads('i' + self.read(4)) bytes = self.read(n) self.append(decode_long(bytes)) dispatch[LONG4] = load_long4 def load_float(self): self.append(float(self.readline()[:-1])) dispatch[FLOAT] = load_float def load_binfloat(self, unpack=struct.unpack): self.append(unpack('>d', self.read(8))[0]) dispatch[BINFLOAT] = load_binfloat def load_string(self): rep = self.readline()[:-1] for q in "\"'": # double or single quote if rep.startswith(q): if not rep.endswith(q): raise ValueError, "insecure string pickle" rep = rep[len(q):-len(q)] break else: raise ValueError, "insecure string pickle" self.append(rep.decode("string-escape")) dispatch[STRING] = load_string def load_binstring(self): len = mloads('i' + self.read(4)) self.append(self.read(len)) dispatch[BINSTRING] = load_binstring def load_unicode(self): self.append(unicode(self.readline()[:-1],'raw-unicode-escape')) dispatch[UNICODE] = load_unicode def load_binunicode(self): len = mloads('i' + self.read(4)) self.append(unicode(self.read(len),'utf-8')) dispatch[BINUNICODE] = load_binunicode def load_short_binstring(self): len = ord(self.read(1)) self.append(self.read(len)) dispatch[SHORT_BINSTRING] = load_short_binstring def load_tuple(self): k = self.marker() self.stack[k:] = [tuple(self.stack[k+1:])] dispatch[TUPLE] = load_tuple def load_empty_tuple(self): self.stack.append(()) dispatch[EMPTY_TUPLE] = load_empty_tuple def load_tuple1(self): self.stack[-1] = (self.stack[-1],) dispatch[TUPLE1] = load_tuple1 def load_tuple2(self): self.stack[-2:] = [(self.stack[-2], self.stack[-1])] dispatch[TUPLE2] = load_tuple2 def load_tuple3(self): self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])] dispatch[TUPLE3] = load_tuple3 def load_empty_list(self): self.stack.append([]) dispatch[EMPTY_LIST] = load_empty_list def load_empty_dictionary(self): self.stack.append({}) dispatch[EMPTY_DICT] = load_empty_dictionary def load_list(self): k = self.marker() self.stack[k:] = [self.stack[k+1:]] dispatch[LIST] = load_list def load_dict(self): k = self.marker() d = {} items = self.stack[k+1:] for i in range(0, len(items), 2): key = items[i] value = items[i+1] d[key] = value self.stack[k:] = [d] dispatch[DICT] = load_dict # INST and OBJ differ only in how they get a class object. It's not # only sensible to do the rest in a common routine, the two routines # previously diverged and grew different bugs. # klass is the class to instantiate, and k points to the topmost mark # object, following which are the arguments for klass.__init__. def _instantiate(self, klass, k): args = tuple(self.stack[k+1:]) del self.stack[k:] instantiated = 0 if (not args and type(klass) is ClassType and not hasattr(klass, "__getinitargs__")): try: value = _EmptyClass() value.__class__ = klass instantiated = 1 except RuntimeError: # In restricted execution, assignment to inst.__class__ is # prohibited pass if not instantiated: try: value = klass(*args) except TypeError, err: raise TypeError, "in constructor for %s: %s" % ( klass.__name__, str(err)), sys.exc_info()[2] self.append(value) def load_inst(self): module = self.readline()[:-1] name = self.readline()[:-1] klass = self.find_class(module, name) self._instantiate(klass, self.marker()) dispatch[INST] = load_inst def load_obj(self): # Stack is ... markobject classobject arg1 arg2 ... k = self.marker() klass = self.stack.pop(k+1) self._instantiate(klass, k) dispatch[OBJ] = load_obj def load_newobj(self): args = self.stack.pop() cls = self.stack[-1] obj = cls.__new__(cls, *args) self.stack[-1] = obj dispatch[NEWOBJ] = load_newobj def load_global(self): module = self.readline()[:-1] name = self.readline()[:-1] klass = self.find_class(module, name) self.append(klass) dispatch[GLOBAL] = load_global def load_ext1(self): code = ord(self.read(1)) self.get_extension(code) dispatch[EXT1] = load_ext1 def load_ext2(self): code = mloads('i' + self.read(2) + '\000\000') self.get_extension(code) dispatch[EXT2] = load_ext2 def load_ext4(self): code = mloads('i' + self.read(4)) self.get_extension(code) dispatch[EXT4] = load_ext4 def get_extension(self, code): nil = [] obj = _extension_cache.get(code, nil) if obj is not nil: self.append(obj) return key = _inverted_registry.get(code) if not key: raise ValueError("unregistered extension code %d" % code) obj = self.find_class(*key) _extension_cache[code] = obj self.append(obj) def find_class(self, module, name): # Subclasses may override this __import__(module) mod = sys.modules[module] klass = getattr(mod, name) return klass def load_reduce(self): stack = self.stack args = stack.pop() func = stack[-1] if args is None: # A hack for Jim Fulton's ExtensionClass, now deprecated warnings.warn("__basicnew__ special case is deprecated", DeprecationWarning) value = func.__basicnew__() else: value = func(*args) stack[-1] = value dispatch[REDUCE] = load_reduce def load_pop(self): del self.stack[-1] dispatch[POP] = load_pop def load_pop_mark(self): k = self.marker() del self.stack[k:] dispatch[POP_MARK] = load_pop_mark def load_dup(self): self.append(self.stack[-1]) dispatch[DUP] = load_dup def load_get(self): self.append(self.memo[self.readline()[:-1]]) dispatch[GET] = load_get def load_binget(self): i = ord(self.read(1)) self.append(self.memo[repr(i)]) dispatch[BINGET] = load_binget def load_long_binget(self): i = mloads('i' + self.read(4)) self.append(self.memo[repr(i)]) dispatch[LONG_BINGET] = load_long_binget def load_put(self): self.memo[self.readline()[:-1]] = self.stack[-1] dispatch[PUT] = load_put def load_binput(self): i = ord(self.read(1)) self.memo[repr(i)] = self.stack[-1] dispatch[BINPUT] = load_binput def load_long_binput(self): i = mloads('i' + self.read(4)) self.memo[repr(i)] = self.stack[-1] dispatch[LONG_BINPUT] = load_long_binput def load_append(self): stack = self.stack value = stack.pop() list = stack[-1] list.append(value) dispatch[APPEND] = load_append def load_appends(self): stack = self.stack mark = self.marker() list = stack[mark - 1] list.extend(stack[mark + 1:]) del stack[mark:] dispatch[APPENDS] = load_appends def load_setitem(self): stack = self.stack value = stack.pop() key = stack.pop() dict = stack[-1] dict[key] = value dispatch[SETITEM] = load_setitem def load_setitems(self): stack = self.stack mark = self.marker() dict = stack[mark - 1] for i in range(mark + 1, len(stack), 2): dict[stack[i]] = stack[i + 1] del stack[mark:] dispatch[SETITEMS] = load_setitems def load_build(self): stack = self.stack state = stack.pop() inst = stack[-1] setstate = getattr(inst, "__setstate__", None) if setstate: setstate(state) return slotstate = None if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if state: try: inst.__dict__.update(state) except RuntimeError: # XXX In restricted execution, the instance's __dict__ # is not accessible. Use the old way of unpickling # the instance variables. This is a semantic # difference when unpickling in restricted # vs. unrestricted modes. # Note, however, that cPickle has never tried to do the # .update() business, and always uses # PyObject_SetItem(inst.__dict__, key, value) in a # loop over state.items(). for k, v in state.items(): setattr(inst, k, v) if slotstate: for k, v in slotstate.items(): setattr(inst, k, v) dispatch[BUILD] = load_build def load_mark(self): self.append(self.mark) dispatch[MARK] = load_mark def load_stop(self): value = self.stack.pop() raise _Stop(value) dispatch[STOP] = load_stop # Helper class for load_inst/load_obj class _EmptyClass: pass # Encode/decode longs in linear time. import binascii as _binascii def encode_long(x): r"""Encode a long to a two's complement little-endian binary string. Note that 0L is a special case, returning an empty string, to save a byte in the LONG1 pickling context. >>> encode_long(0L) '' >>> encode_long(255L) '\xff\x00' >>> encode_long(32767L) '\xff\x7f' >>> encode_long(-256L) '\x00\xff' >>> encode_long(-32768L) '\x00\x80' >>> encode_long(-128L) '\x80' >>> encode_long(127L) '\x7f' >>> """ if x == 0: return '' if x > 0: ashex = hex(x) assert ashex.startswith("0x") njunkchars = 2 + ashex.endswith('L') nibbles = len(ashex) - njunkchars if nibbles & 1: # need an even # of nibbles for unhexlify ashex = "0x0" + ashex[2:] elif int(ashex[2], 16) >= 8: # "looks negative", so need a byte of sign bits ashex = "0x00" + ashex[2:] else: # Build the 256's-complement: (1L << nbytes) + x. The trick is # to find the number of bytes in linear time (although that should # really be a constant-time task). ashex = hex(-x) assert ashex.startswith("0x") njunkchars = 2 + ashex.endswith('L') nibbles = len(ashex) - njunkchars if nibbles & 1: # Extend to a full byte. nibbles += 1 nbits = nibbles * 4 x += 1L << nbits assert x > 0 ashex = hex(x) njunkchars = 2 + ashex.endswith('L') newnibbles = len(ashex) - njunkchars if newnibbles < nibbles: ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:] if int(ashex[2], 16) < 8: # "looks positive", so need a byte of sign bits ashex = "0xff" + ashex[2:] if ashex.endswith('L'): ashex = ashex[2:-1] else: ashex = ashex[2:] assert len(ashex) & 1 == 0, (x, ashex) binary = _binascii.unhexlify(ashex) return binary[::-1] def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. >>> decode_long('') 0L >>> decode_long("\xff\x00") 255L >>> decode_long("\xff\x7f") 32767L >>> decode_long("\x00\xff") -256L >>> decode_long("\x00\x80") -32768L >>> decode_long("\x80") -128L >>> decode_long("\x7f") 127L """ nbytes = len(data) if nbytes == 0: return 0L ashex = _binascii.hexlify(data[::-1]) n = long(ashex, 16) # quadratic time before Python 2.3; linear now if data[-1] >= '\x80': n -= 1L << (nbytes * 8) return n # Shorthands try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def dump(obj, file, protocol=None, bin=None): Pickler(file, protocol, bin).dump(obj) def dumps(obj, protocol=None, bin=None): file = StringIO() Pickler(file, protocol, bin).dump(obj) return file.getvalue() def load(file): return Unpickler(file).load() def loads(str): file = StringIO(str) return Unpickler(file).load() # Doctest def _test(): import doctest return doctest.testmod() if __name__ == "__main__": _test()
Python
# Copyright (c) 2004 Python Software Foundation. # All rights reserved. # Written by Eric Price <eprice at tjhsst.edu> # and Facundo Batista <facundo at taniquetil.com.ar> # and Raymond Hettinger <python at rcn.com> # and Aahz <aahz at pobox.com> # and Tim Peters # This module is currently Py2.3 compatible and should be kept that way # unless a major compelling advantage arises. IOW, 2.3 compatibility is # strongly preferred, but not guaranteed. # Also, this module should be kept in sync with the latest updates of # the IBM specification as it evolves. Those updates will be treated # as bug fixes (deviation from the spec is a compatibility, usability # bug) and will be backported. At this point the spec is stabilizing # and the updates are becoming fewer, smaller, and less significant. """ This is a Py2.3 implementation of decimal floating point arithmetic based on the General Decimal Arithmetic Specification: www2.hursley.ibm.com/decimal/decarith.html and IEEE standard 854-1987: www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html Decimal floating point has finite precision with arbitrarily large bounds. The purpose of the module is to support arithmetic using familiar "schoolhouse" rules and to avoid the some of tricky representation issues associated with binary floating point. The package is especially useful for financial applications or for contexts where users have expectations that are at odds with binary floating point (for instance, in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead of the expected Decimal("0.00") returned by decimal floating point). Here are some examples of using the decimal module: >>> from decimal import * >>> setcontext(ExtendedContext) >>> Decimal(0) Decimal("0") >>> Decimal("1") Decimal("1") >>> Decimal("-.0123") Decimal("-0.0123") >>> Decimal(123456) Decimal("123456") >>> Decimal("123.45e12345678901234567890") Decimal("1.2345E+12345678901234567892") >>> Decimal("1.33") + Decimal("1.27") Decimal("2.60") >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41") Decimal("-2.20") >>> dig = Decimal(1) >>> print dig / Decimal(3) 0.333333333 >>> getcontext().prec = 18 >>> print dig / Decimal(3) 0.333333333333333333 >>> print dig.sqrt() 1 >>> print Decimal(3).sqrt() 1.73205080756887729 >>> print Decimal(3) ** 123 4.85192780976896427E+58 >>> inf = Decimal(1) / Decimal(0) >>> print inf Infinity >>> neginf = Decimal(-1) / Decimal(0) >>> print neginf -Infinity >>> print neginf + inf NaN >>> print neginf * inf -Infinity >>> print dig / 0 Infinity >>> getcontext().traps[DivisionByZero] = 1 >>> print dig / 0 Traceback (most recent call last): ... ... ... DivisionByZero: x / 0 >>> c = Context() >>> c.traps[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> c.divide(Decimal(0), Decimal(0)) Decimal("NaN") >>> c.traps[InvalidOperation] = 1 >>> print c.flags[InvalidOperation] 1 >>> c.flags[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> print c.divide(Decimal(0), Decimal(0)) Traceback (most recent call last): ... ... ... InvalidOperation: 0 / 0 >>> print c.flags[InvalidOperation] 1 >>> c.flags[InvalidOperation] = 0 >>> c.traps[InvalidOperation] = 0 >>> print c.divide(Decimal(0), Decimal(0)) NaN >>> print c.flags[InvalidOperation] 1 >>> """ __all__ = [ # Two major classes 'Decimal', 'Context', # Contexts 'DefaultContext', 'BasicContext', 'ExtendedContext', # Exceptions 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', # Constants for use in setting up contexts 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', # Functions for manipulating contexts 'setcontext', 'getcontext' ] import copy #Rounding ROUND_DOWN = 'ROUND_DOWN' ROUND_HALF_UP = 'ROUND_HALF_UP' ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' ROUND_CEILING = 'ROUND_CEILING' ROUND_FLOOR = 'ROUND_FLOOR' ROUND_UP = 'ROUND_UP' ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' #Rounding decision (not part of the public API) NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end. #Errors class DecimalException(ArithmeticError): """Base exception class. Used exceptions derive from this. If an exception derives from another exception besides this (such as Underflow (Inexact, Rounded, Subnormal) that indicates that it is only called if the others are present. This isn't actually used for anything, though. handle -- Called when context._raise_error is called and the trap_enabler is set. First argument is self, second is the context. More arguments can be given, those being after the explanation in _raise_error (For example, context._raise_error(NewError, '(-x)!', self._sign) would call NewError().handle(context, self._sign).) To define a new exception, it should be sufficient to have it derive from DecimalException. """ def handle(self, context, *args): pass class Clamped(DecimalException): """Exponent of a 0 changed to fit bounds. This occurs and signals clamped if the exponent of a result has been altered in order to fit the constraints of a specific concrete representation. This may occur when the exponent of a zero result would be outside the bounds of a representation, or when a large normal number would have an encoded exponent that cannot be represented. In this latter case, the exponent is reduced to fit and the corresponding number of zero digits are appended to the coefficient ("fold-down"). """ class InvalidOperation(DecimalException): """An invalid operation was performed. Various bad things cause this: Something creates a signaling NaN -INF + INF 0 * (+-)INF (+-)INF / (+-)INF x % 0 (+-)INF % x x._rescale( non-integer ) sqrt(-x) , x > 0 0 ** 0 x ** (non-integer) x ** (+-)INF An operand is invalid """ def handle(self, context, *args): if args: if args[0] == 1: #sNaN, must drop 's' but keep diagnostics return Decimal( (args[1]._sign, args[1]._int, 'n') ) return NaN class ConversionSyntax(InvalidOperation): """Trying to convert badly formed string. This occurs and signals invalid-operation if an string is being converted to a number and it does not conform to the numeric string syntax. The result is [0,qNaN]. """ def handle(self, context, *args): return (0, (0,), 'n') #Passed to something which uses a tuple. class DivisionByZero(DecimalException, ZeroDivisionError): """Division by 0. This occurs and signals division-by-zero if division of a finite number by zero was attempted (during a divide-integer or divide operation, or a power operation with negative right-hand operand), and the dividend was not zero. The result of the operation is [sign,inf], where sign is the exclusive or of the signs of the operands for divide, or is 1 for an odd power of -0, for power. """ def handle(self, context, sign, double = None, *args): if double is not None: return (Infsign[sign],)*2 return Infsign[sign] class DivisionImpossible(InvalidOperation): """Cannot perform the division adequately. This occurs and signals invalid-operation if the integer result of a divide-integer or remainder operation had too many digits (would be longer than precision). The result is [0,qNaN]. """ def handle(self, context, *args): return (NaN, NaN) class DivisionUndefined(InvalidOperation, ZeroDivisionError): """Undefined result of division. This occurs and signals invalid-operation if division by zero was attempted (during a divide-integer, divide, or remainder operation), and the dividend is also zero. The result is [0,qNaN]. """ def handle(self, context, tup=None, *args): if tup is not None: return (NaN, NaN) #for 0 %0, 0 // 0 return NaN class Inexact(DecimalException): """Had to round, losing information. This occurs and signals inexact whenever the result of an operation is not exact (that is, it needed to be rounded and any discarded digits were non-zero), or if an overflow or underflow condition occurs. The result in all cases is unchanged. The inexact signal may be tested (or trapped) to determine if a given operation (or sequence of operations) was inexact. """ pass class InvalidContext(InvalidOperation): """Invalid context. Unknown rounding, for example. This occurs and signals invalid-operation if an invalid context was detected during an operation. This can occur if contexts are not checked on creation and either the precision exceeds the capability of the underlying concrete representation or an unknown or unsupported rounding was specified. These aspects of the context need only be checked when the values are required to be used. The result is [0,qNaN]. """ def handle(self, context, *args): return NaN class Rounded(DecimalException): """Number got rounded (not necessarily changed during rounding). This occurs and signals rounded whenever the result of an operation is rounded (that is, some zero or non-zero digits were discarded from the coefficient), or if an overflow or underflow condition occurs. The result in all cases is unchanged. The rounded signal may be tested (or trapped) to determine if a given operation (or sequence of operations) caused a loss of precision. """ pass class Subnormal(DecimalException): """Exponent < Emin before rounding. This occurs and signals subnormal whenever the result of a conversion or operation is subnormal (that is, its adjusted exponent is less than Emin, before any rounding). The result in all cases is unchanged. The subnormal signal may be tested (or trapped) to determine if a given or operation (or sequence of operations) yielded a subnormal result. """ pass class Overflow(Inexact, Rounded): """Numerical overflow. This occurs and signals overflow if the adjusted exponent of a result (from a conversion or from an operation that is not an attempt to divide by zero), after rounding, would be greater than the largest value that can be handled by the implementation (the value Emax). The result depends on the rounding mode: For round-half-up and round-half-even (and for round-half-down and round-up, if implemented), the result of the operation is [sign,inf], where sign is the sign of the intermediate result. For round-down, the result is the largest finite number that can be represented in the current precision, with the sign of the intermediate result. For round-ceiling, the result is the same as for round-down if the sign of the intermediate result is 1, or is [0,inf] otherwise. For round-floor, the result is the same as for round-down if the sign of the intermediate result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded will also be raised. """ def handle(self, context, sign, *args): if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_HALF_DOWN, ROUND_UP): return Infsign[sign] if sign == 0: if context.rounding == ROUND_CEILING: return Infsign[sign] return Decimal((sign, (9,)*context.prec, context.Emax-context.prec+1)) if sign == 1: if context.rounding == ROUND_FLOOR: return Infsign[sign] return Decimal( (sign, (9,)*context.prec, context.Emax-context.prec+1)) class Underflow(Inexact, Rounded, Subnormal): """Numerical underflow with result rounded to 0. This occurs and signals underflow if a result is inexact and the adjusted exponent of the result would be smaller (more negative) than the smallest value that can be handled by the implementation (the value Emin). That is, the result is both inexact and subnormal. The result after an underflow will be a subnormal number rounded, if necessary, so that its exponent is not less than Etiny. This may result in 0 with the sign of the intermediate result and an exponent of Etiny. In all cases, Inexact, Rounded, and Subnormal will also be raised. """ # List of public traps and flags _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, Underflow, InvalidOperation, Subnormal] # Map conditions (per the spec) to signals _condition_map = {ConversionSyntax:InvalidOperation, DivisionImpossible:InvalidOperation, DivisionUndefined:InvalidOperation, InvalidContext:InvalidOperation} ##### Context Functions ####################################### # The getcontext() and setcontext() function manage access to a thread-local # current context. Py2.4 offers direct support for thread locals. If that # is not available, use threading.currentThread() which is slower but will # work for older Pythons. If threads are not part of the build, create a # mock threading object with threading.local() returning the module namespace. try: import threading except ImportError: # Python was compiled without threads; create a mock object instead import sys class MockThreading: def local(self, sys=sys): return sys.modules[__name__] threading = MockThreading() del sys, MockThreading try: threading.local except AttributeError: #To fix reloading, force it to create a new context #Old contexts have different exceptions in their dicts, making problems. if hasattr(threading.currentThread(), '__decimal_context__'): del threading.currentThread().__decimal_context__ def setcontext(context): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() context.clear_flags() threading.currentThread().__decimal_context__ = context def getcontext(): """Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext. """ try: return threading.currentThread().__decimal_context__ except AttributeError: context = Context() threading.currentThread().__decimal_context__ = context return context else: local = threading.local() if hasattr(local, '__decimal_context__'): del local.__decimal_context__ def getcontext(_local=local): """Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext. """ try: return _local.__decimal_context__ except AttributeError: context = Context() _local.__decimal_context__ = context return context def setcontext(context, _local=local): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() context.clear_flags() _local.__decimal_context__ = context del threading, local # Don't contaminate the namespace ##### Decimal class ########################################### class Decimal(object): """Floating point class for decimal arithmetic.""" __slots__ = ('_exp','_int','_sign', '_is_special') # Generally, the value of the Decimal instance is given by # (-1)**_sign * _int * 10**_exp # Special values are signified by _is_special == True # We're immutable, so use __new__ not __init__ def __new__(cls, value="0", context=None): """Create a decimal point instance. >>> Decimal('3.14') # string input Decimal("3.14") >>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent) Decimal("3.14") >>> Decimal(314) # int or long Decimal("314") >>> Decimal(Decimal(314)) # another decimal instance Decimal("314") """ self = object.__new__(cls) self._is_special = False # From an internal working value if isinstance(value, _WorkRep): self._sign = value.sign self._int = tuple(map(int, str(value.int))) self._exp = int(value.exp) return self # From another decimal if isinstance(value, Decimal): self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self # From an integer if isinstance(value, (int,long)): if value >= 0: self._sign = 0 else: self._sign = 1 self._exp = 0 self._int = tuple(map(int, str(abs(value)))) return self # tuple/list conversion (possibly from as_tuple()) if isinstance(value, (list,tuple)): if len(value) != 3: raise ValueError, 'Invalid arguments' if value[0] not in [0,1]: raise ValueError, 'Invalid sign' for digit in value[1]: if not isinstance(digit, (int,long)) or digit < 0: raise ValueError, "The second value in the tuple must be composed of non negative integer elements." self._sign = value[0] self._int = tuple(value[1]) if value[2] in ('F','n','N'): self._exp = value[2] self._is_special = True else: self._exp = int(value[2]) return self if isinstance(value, float): raise TypeError("Cannot convert float to Decimal. " + "First convert the float to a string") # Other argument types may require the context during interpretation if context is None: context = getcontext() # From a string # REs insist on real strings, so we can too. if isinstance(value, basestring): if _isinfinity(value): self._exp = 'F' self._int = (0,) self._is_special = True if _isinfinity(value) == 1: self._sign = 0 else: self._sign = 1 return self if _isnan(value): sig, sign, diag = _isnan(value) self._is_special = True if len(diag) > context.prec: #Diagnostic info too long self._sign, self._int, self._exp = \ context._raise_error(ConversionSyntax) return self if sig == 1: self._exp = 'n' #qNaN else: #sig == 2 self._exp = 'N' #sNaN self._sign = sign self._int = tuple(map(int, diag)) #Diagnostic info return self try: self._sign, self._int, self._exp = _string2exact(value) except ValueError: self._is_special = True self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) return self raise TypeError("Cannot convert %r to Decimal" % value) def _isnan(self): """Returns whether the number is not actually one. 0 if a number 1 if NaN 2 if sNaN """ if self._is_special: exp = self._exp if exp == 'n': return 1 elif exp == 'N': return 2 return 0 def _isinfinity(self): """Returns whether the number is infinite 0 if finite or not a number 1 if +INF -1 if -INF """ if self._exp == 'F': if self._sign: return -1 return 1 return 0 def _check_nans(self, other = None, context=None): """Returns whether the number is not actually one. if self, other are sNaN, signal if self, other are NaN return nan return 0 Done before operations. """ self_is_nan = self._isnan() if other is None: other_is_nan = False else: other_is_nan = other._isnan() if self_is_nan or other_is_nan: if context is None: context = getcontext() if self_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, self) if other_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, other) if self_is_nan: return self return other return 0 def __nonzero__(self): """Is the number non-zero? 0 if self == 0 1 if self != 0 """ if self._is_special: return 1 return sum(self._int) != 0 def __cmp__(self, other, context=None): other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return 1 # Comparison involving NaN's always reports self > other # INF = INF return cmp(self._isinfinity(), other._isinfinity()) if not self and not other: return 0 #If both 0, sign comparison isn't certain. #If different signs, neg one is less if other._sign < self._sign: return -1 if self._sign < other._sign: return 1 self_adjusted = self.adjusted() other_adjusted = other.adjusted() if self_adjusted == other_adjusted and \ self._int + (0,)*(self._exp - other._exp) == \ other._int + (0,)*(other._exp - self._exp): return 0 #equal, except in precision. ([0]*(-x) = []) elif self_adjusted > other_adjusted and self._int[0] != 0: return (-1)**self._sign elif self_adjusted < other_adjusted and other._int[0] != 0: return -((-1)**self._sign) # Need to round, so make sure we have a valid context if context is None: context = getcontext() context = context._shallow_copy() rounding = context._set_rounding(ROUND_UP) #round away from 0 flags = context._ignore_all_flags() res = self.__sub__(other, context=context) context._regard_flags(*flags) context.rounding = rounding if not res: return 0 elif res._sign: return -1 return 1 def __eq__(self, other): if not isinstance(other, (Decimal, int, long)): return NotImplemented return self.__cmp__(other) == 0 def __ne__(self, other): if not isinstance(other, (Decimal, int, long)): return NotImplemented return self.__cmp__(other) != 0 def compare(self, other, context=None): """Compares one to another. -1 => a < b 0 => a = b 1 => a > b NaN => one is NaN Like __cmp__, but returns Decimal instances. """ other = _convert_other(other) if other is NotImplemented: return other #compare(NaN, NaN) = NaN if (self._is_special or other and other._is_special): ans = self._check_nans(other, context) if ans: return ans return Decimal(self.__cmp__(other, context)) def __hash__(self): """x.__hash__() <==> hash(x)""" # Decimal integers must hash the same as the ints # Non-integer decimals are normalized and hashed as strings # Normalization assures that hast(100E-1) == hash(10) if self._is_special: if self._isnan(): raise TypeError('Cannot hash a NaN value.') return hash(str(self)) i = int(self) if self == Decimal(i): return hash(i) assert self.__nonzero__() # '-0' handled by integer case return hash(str(self.normalize())) def as_tuple(self): """Represents the number as a triple tuple. To show the internals exactly as they are. """ return (self._sign, self._int, self._exp) def __repr__(self): """Represents the number as an instance of Decimal.""" # Invariant: eval(repr(d)) == d return 'Decimal("%s")' % str(self) def __str__(self, eng = 0, context=None): """Return string representation of the number in scientific notation. Captures all of the information in the underlying representation. """ if self._isnan(): minus = '-'*self._sign if self._int == (0,): info = '' else: info = ''.join(map(str, self._int)) if self._isnan() == 2: return minus + 'sNaN' + info return minus + 'NaN' + info if self._isinfinity(): minus = '-'*self._sign return minus + 'Infinity' if context is None: context = getcontext() tmp = map(str, self._int) numdigits = len(self._int) leftdigits = self._exp + numdigits if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY if self._exp < 0 and self._exp >= -6: #short, no need for e/E s = '-'*self._sign + '0.' + '0'*(abs(self._exp)) return s #exp is closest mult. of 3 >= self._exp exp = ((self._exp - 1)// 3 + 1) * 3 if exp != self._exp: s = '0.'+'0'*(exp - self._exp) else: s = '0' if exp != 0: if context.capitals: s += 'E' else: s += 'e' if exp > 0: s += '+' #0.0e+3, not 0.0e3 s += str(exp) s = '-'*self._sign + s return s if eng: dotplace = (leftdigits-1)%3+1 adjexp = leftdigits -1 - (leftdigits-1)%3 else: adjexp = leftdigits-1 dotplace = 1 if self._exp == 0: pass elif self._exp < 0 and adjexp >= 0: tmp.insert(leftdigits, '.') elif self._exp < 0 and adjexp >= -6: tmp[0:0] = ['0'] * int(-leftdigits) tmp.insert(0, '0.') else: if numdigits > dotplace: tmp.insert(dotplace, '.') elif numdigits < dotplace: tmp.extend(['0']*(dotplace-numdigits)) if adjexp: if not context.capitals: tmp.append('e') else: tmp.append('E') if adjexp > 0: tmp.append('+') tmp.append(str(adjexp)) if eng: while tmp[0:1] == ['0']: tmp[0:1] = [] if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e': tmp[0:0] = ['0'] if self._sign: tmp.insert(0, '-') return ''.join(tmp) def to_eng_string(self, context=None): """Convert to engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. Same rules for when in exponential and when as a value as in __str__. """ return self.__str__(eng=1, context=context) def __neg__(self, context=None): """Returns a copy with the sign switched. Rounds, if it has reason. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if not self: # -Decimal('0') is Decimal('0'), not Decimal('-0') sign = 0 elif self._sign: sign = 0 else: sign = 1 if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return Decimal((sign, self._int, self._exp))._fix(context) return Decimal( (sign, self._int, self._exp)) def __pos__(self, context=None): """Returns a copy, unless it is a sNaN. Rounds the number (if more then precision digits) """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans sign = self._sign if not self: # + (-0) = 0 sign = 0 if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: ans = self._fix(context) else: ans = Decimal(self) ans._sign = sign return ans def __abs__(self, round=1, context=None): """Returns the absolute value of self. If the second argument is 0, do not round. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if not round: if context is None: context = getcontext() context = context._shallow_copy() context._set_rounding_decision(NEVER_ROUND) if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans def __add__(self, other, context=None): """Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors. """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): #If both INF, same sign => same as both, opposite => error. if self._sign != other._sign and other._isinfinity(): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other) #Can't both be infinity here shouldround = context._rounding_decision == ALWAYS_ROUND exp = min(self._exp, other._exp) negativezero = 0 if context.rounding == ROUND_FLOOR and self._sign != other._sign: #If the answer is 0, the sign should be negative, in this case. negativezero = 1 if not self and not other: sign = min(self._sign, other._sign) if negativezero: sign = 1 return Decimal( (sign, (0,), exp)) if not self: exp = max(exp, other._exp - context.prec-1) ans = other._rescale(exp, watchexp=0, context=context) if shouldround: ans = ans._fix(context) return ans if not other: exp = max(exp, self._exp - context.prec-1) ans = self._rescale(exp, watchexp=0, context=context) if shouldround: ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) op1, op2 = _normalize(op1, op2, shouldround, context.prec) result = _WorkRep() if op1.sign != op2.sign: # Equal and opposite if op1.int == op2.int: if exp < context.Etiny(): exp = context.Etiny() context._raise_error(Clamped) return Decimal((negativezero, (0,), exp)) if op1.int < op2.int: op1, op2 = op2, op1 #OK, now abs(op1) > abs(op2) if op1.sign == 1: result.sign = 1 op1.sign, op2.sign = op2.sign, op1.sign else: result.sign = 0 #So we know the sign, and op1 > 0. elif op1.sign == 1: result.sign = 1 op1.sign, op2.sign = (0, 0) else: result.sign = 0 #Now, op1 > abs(op2) > 0 if op2.sign == 0: result.int = op1.int + op2.int else: result.int = op1.int - op2.int result.exp = op1.exp ans = Decimal(result) if shouldround: ans = ans._fix(context) return ans __radd__ = __add__ def __sub__(self, other, context=None): """Return self + (-other)""" other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context=context) if ans: return ans # -Decimal(0) = Decimal(0), which we don't want since # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.) # so we change the sign directly to a copy tmp = Decimal(other) tmp._sign = 1-tmp._sign return self.__add__(tmp, context=context) def __rsub__(self, other, context=None): """Return other + (-self)""" other = _convert_other(other) if other is NotImplemented: return other tmp = Decimal(self) tmp._sign = 1 - tmp._sign return other.__add__(tmp, context=context) def _increment(self, round=1, context=None): """Special case of add, adding 1eExponent Since it is common, (rounding, for example) this adds (sign)*one E self._exp to the number more efficiently than add. For example: Decimal('5.624e10')._increment() == Decimal('5.625e10') """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans return Decimal(self) # Must be infinite, and incrementing makes no difference L = list(self._int) L[-1] += 1 spot = len(L)-1 while L[spot] == 10: L[spot] = 0 if spot == 0: L[0:0] = [1] break L[spot-1] += 1 spot -= 1 ans = Decimal((self._sign, L, self._exp)) if context is None: context = getcontext() if round and context._rounding_decision == ALWAYS_ROUND: ans = ans._fix(context) return ans def __mul__(self, other, context=None): """Return self * other. (+-) INF * 0 (or its reverse) raise InvalidOperation. """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() resultsign = self._sign ^ other._sign if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if not other: return context._raise_error(InvalidOperation, '(+-)INF * 0') return Infsign[resultsign] if other._isinfinity(): if not self: return context._raise_error(InvalidOperation, '0 * (+-)INF') return Infsign[resultsign] resultexp = self._exp + other._exp shouldround = context._rounding_decision == ALWAYS_ROUND # Special case for multiplying by zero if not self or not other: ans = Decimal((resultsign, (0,), resultexp)) if shouldround: #Fixing in case the exponent is out of bounds ans = ans._fix(context) return ans # Special case for multiplying by power of 10 if self._int == (1,): ans = Decimal((resultsign, other._int, resultexp)) if shouldround: ans = ans._fix(context) return ans if other._int == (1,): ans = Decimal((resultsign, self._int, resultexp)) if shouldround: ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp)) if shouldround: ans = ans._fix(context) return ans __rmul__ = __mul__ def __div__(self, other, context=None): """Return self / other.""" return self._divide(other, context=context) __truediv__ = __div__ def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision. divmod: 0 => true division 1 => (a //b, a%b) 2 => a //b 3 => a%b Actually, if divmod is 2 or 3 a tuple is returned, but errors for computing the other value are not raised. """ other = _convert_other(other) if other is NotImplemented: if divmod in (0, 1): return NotImplemented return (NotImplemented, NotImplemented) if context is None: context = getcontext() sign = self._sign ^ other._sign if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: if divmod: return (ans, ans) return ans if self._isinfinity() and other._isinfinity(): if divmod: return (context._raise_error(InvalidOperation, '(+-)INF // (+-)INF'), context._raise_error(InvalidOperation, '(+-)INF % (+-)INF')) return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') if self._isinfinity(): if divmod == 1: return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x')) elif divmod == 2: return (Infsign[sign], NaN) elif divmod == 3: return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x')) return Infsign[sign] if other._isinfinity(): if divmod: return (Decimal((sign, (0,), 0)), Decimal(self)) context._raise_error(Clamped, 'Division by infinity') return Decimal((sign, (0,), context.Etiny())) # Special cases for zeroes if not self and not other: if divmod: return context._raise_error(DivisionUndefined, '0 / 0', 1) return context._raise_error(DivisionUndefined, '0 / 0') if not self: if divmod: otherside = Decimal(self) otherside._exp = min(self._exp, other._exp) return (Decimal((sign, (0,), 0)), otherside) exp = self._exp - other._exp if exp < context.Etiny(): exp = context.Etiny() context._raise_error(Clamped, '0e-x / y') if exp > context.Emax: exp = context.Emax context._raise_error(Clamped, '0e+x / y') return Decimal( (sign, (0,), exp) ) if not other: if divmod: return context._raise_error(DivisionByZero, 'divmod(x,0)', sign, 1) return context._raise_error(DivisionByZero, 'x / 0', sign) #OK, so neither = 0, INF or NaN shouldround = context._rounding_decision == ALWAYS_ROUND #If we're dividing into ints, and self < other, stop. #self.__abs__(0) does not round. if divmod and (self.__abs__(0, context) < other.__abs__(0, context)): if divmod == 1 or divmod == 3: exp = min(self._exp, other._exp) ans2 = self._rescale(exp, context=context, watchexp=0) if shouldround: ans2 = ans2._fix(context) return (Decimal( (sign, (0,), 0) ), ans2) elif divmod == 2: #Don't round the mod part, if we don't need it. return (Decimal( (sign, (0,), 0) ), Decimal(self)) op1 = _WorkRep(self) op2 = _WorkRep(other) op1, op2, adjust = _adjust_coefficients(op1, op2) res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) ) if divmod and res.exp > context.prec + 1: return context._raise_error(DivisionImpossible) prec_limit = 10 ** context.prec while 1: while op2.int <= op1.int: res.int += 1 op1.int -= op2.int if res.exp == 0 and divmod: if res.int >= prec_limit and shouldround: return context._raise_error(DivisionImpossible) otherside = Decimal(op1) frozen = context._ignore_all_flags() exp = min(self._exp, other._exp) otherside = otherside._rescale(exp, context=context, watchexp=0) context._regard_flags(*frozen) if shouldround: otherside = otherside._fix(context) return (Decimal(res), otherside) if op1.int == 0 and adjust >= 0 and not divmod: break if res.int >= prec_limit and shouldround: if divmod: return context._raise_error(DivisionImpossible) shouldround=1 # Really, the answer is a bit higher, so adding a one to # the end will make sure the rounding is right. if op1.int != 0: res.int *= 10 res.int += 1 res.exp -= 1 break res.int *= 10 res.exp -= 1 adjust += 1 op1.int *= 10 op1.exp -= 1 if res.exp == 0 and divmod and op2.int > op1.int: #Solves an error in precision. Same as a previous block. if res.int >= prec_limit and shouldround: return context._raise_error(DivisionImpossible) otherside = Decimal(op1) frozen = context._ignore_all_flags() exp = min(self._exp, other._exp) otherside = otherside._rescale(exp, context=context) context._regard_flags(*frozen) return (Decimal(res), otherside) ans = Decimal(res) if shouldround: ans = ans._fix(context) return ans def __rdiv__(self, other, context=None): """Swaps self/other and returns __div__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__div__(self, context=context) __rtruediv__ = __rdiv__ def __divmod__(self, other, context=None): """ (self // other, self % other) """ return self._divide(other, 1, context) def __rdivmod__(self, other, context=None): """Swaps self/other and returns __divmod__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__divmod__(self, context=context) def __mod__(self, other, context=None): """ self % other """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self and not other: return context._raise_error(InvalidOperation, 'x % 0') return self._divide(other, 3, context)[1] def __rmod__(self, other, context=None): """Swaps self/other and returns __mod__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__mod__(self, context=context) def remainder_near(self, other, context=None): """ Remainder nearest to 0- abs(remainder-near) <= other/2 """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self and not other: return context._raise_error(InvalidOperation, 'x % 0') if context is None: context = getcontext() # If DivisionImpossible causes an error, do not leave Rounded/Inexact # ignored in the calling function. context = context._shallow_copy() flags = context._ignore_flags(Rounded, Inexact) #keep DivisionImpossible flags (side, r) = self.__divmod__(other, context=context) if r._isnan(): context._regard_flags(*flags) return r context = context._shallow_copy() rounding = context._set_rounding_decision(NEVER_ROUND) if other._sign: comparison = other.__div__(Decimal(-2), context=context) else: comparison = other.__div__(Decimal(2), context=context) context._set_rounding_decision(rounding) context._regard_flags(*flags) s1, s2 = r._sign, comparison._sign r._sign, comparison._sign = 0, 0 if r < comparison: r._sign, comparison._sign = s1, s2 #Get flags now self.__divmod__(other, context=context) return r._fix(context) r._sign, comparison._sign = s1, s2 rounding = context._set_rounding_decision(NEVER_ROUND) (side, r) = self.__divmod__(other, context=context) context._set_rounding_decision(rounding) if r._isnan(): return r decrease = not side._iseven() rounding = context._set_rounding_decision(NEVER_ROUND) side = side.__abs__(context=context) context._set_rounding_decision(rounding) s1, s2 = r._sign, comparison._sign r._sign, comparison._sign = 0, 0 if r > comparison or decrease and r == comparison: r._sign, comparison._sign = s1, s2 context.prec += 1 if len(side.__add__(Decimal(1), context=context)._int) >= context.prec: context.prec -= 1 return context._raise_error(DivisionImpossible)[1] context.prec -= 1 if self._sign == other._sign: r = r.__sub__(other, context=context) else: r = r.__add__(other, context=context) else: r._sign, comparison._sign = s1, s2 return r._fix(context) def __floordiv__(self, other, context=None): """self // other""" return self._divide(other, 2, context)[0] def __rfloordiv__(self, other, context=None): """Swaps self/other and returns __floordiv__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__floordiv__(self, context=context) def __float__(self): """Float representation.""" return float(str(self)) def __int__(self): """Converts self to a int, truncating if necessary.""" if self._is_special: if self._isnan(): context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): raise OverflowError, "Cannot convert infinity to long" if self._exp >= 0: s = ''.join(map(str, self._int)) + '0'*self._exp else: s = ''.join(map(str, self._int))[:self._exp] if s == '': s = '0' sign = '-'*self._sign return int(sign + s) def __long__(self): """Converts to a long. Equivalent to long(int(self)) """ return long(self.__int__()) def _fix(self, context): """Round if it is necessary to keep self within prec precision. Rounds and fixes the exponent. Does not raise on a sNaN. Arguments: self - Decimal instance context - context used. """ if self._is_special: return self if context is None: context = getcontext() prec = context.prec ans = self._fixexponents(context) if len(ans._int) > prec: ans = ans._round(prec, context=context) ans = ans._fixexponents(context) return ans def _fixexponents(self, context): """Fix the exponents and return a copy with the exponent in bounds. Only call if known to not be a special value. """ folddown = context._clamp Emin = context.Emin ans = self ans_adjusted = ans.adjusted() if ans_adjusted < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans = Decimal(self) ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) else: Etop = context.Etop() if folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) else: Emax = context.Emax if ans_adjusted > Emax: if not ans: ans = Decimal(self) ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans def _round(self, prec=None, rounding=None, context=None): """Returns a rounded version of self. You can specify the precision or rounding method. Otherwise, the context determines it. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._isinfinity(): return Decimal(self) if context is None: context = getcontext() if rounding is None: rounding = context.rounding if prec is None: prec = context.prec if not self: if prec <= 0: dig = (0,) exp = len(self._int) - prec + self._exp else: dig = (0,) * prec exp = len(self._int) + self._exp - prec ans = Decimal((self._sign, dig, exp)) context._raise_error(Rounded) return ans if prec == 0: temp = Decimal(self) temp._int = (0,)+temp._int prec = 1 elif prec < 0: exp = self._exp + len(self._int) - prec - 1 temp = Decimal( (self._sign, (0, 1), exp)) prec = 1 else: temp = Decimal(self) numdigits = len(temp._int) if prec == numdigits: return temp # See if we need to extend precision expdiff = prec - numdigits if expdiff > 0: tmp = list(temp._int) tmp.extend([0] * expdiff) ans = Decimal( (temp._sign, tmp, temp._exp - expdiff)) return ans #OK, but maybe all the lost digits are 0. lostdigits = self._int[expdiff:] if lostdigits == (0,) * len(lostdigits): ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff)) #Rounded, but not Inexact context._raise_error(Rounded) return ans # Okay, let's round and lose data this_function = getattr(temp, self._pick_rounding_function[rounding]) #Now we've got the rounding function if prec != context.prec: context = context._shallow_copy() context.prec = prec ans = this_function(prec, expdiff, context) context._raise_error(Rounded) context._raise_error(Inexact, 'Changed in rounding') return ans _pick_rounding_function = {} def _round_down(self, prec, expdiff, context): """Also known as round-towards-0, truncate.""" return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) def _round_half_up(self, prec, expdiff, context, tmp = None): """Rounds 5 up (away from 0)""" if tmp is None: tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff)) if self._int[prec] >= 5: tmp = tmp._increment(round=0, context=context) if len(tmp._int) > prec: return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) return tmp def _round_half_even(self, prec, expdiff, context): """Round 5 to even, rest to nearest.""" tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) half = (self._int[prec] == 5) if half: for digit in self._int[prec+1:]: if digit != 0: half = 0 break if half: if self._int[prec-1] & 1 == 0: return tmp return self._round_half_up(prec, expdiff, context, tmp) def _round_half_down(self, prec, expdiff, context): """Round 5 down""" tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) half = (self._int[prec] == 5) if half: for digit in self._int[prec+1:]: if digit != 0: half = 0 break if half: return tmp return self._round_half_up(prec, expdiff, context, tmp) def _round_up(self, prec, expdiff, context): """Rounds away from 0.""" tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) for digit in self._int[prec:]: if digit != 0: tmp = tmp._increment(round=1, context=context) if len(tmp._int) > prec: return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) else: return tmp return tmp def _round_ceiling(self, prec, expdiff, context): """Rounds up (not away from 0 if negative.)""" if self._sign: return self._round_down(prec, expdiff, context) else: return self._round_up(prec, expdiff, context) def _round_floor(self, prec, expdiff, context): """Rounds down (not towards 0 if negative)""" if not self._sign: return self._round_down(prec, expdiff, context) else: return self._round_up(prec, expdiff, context) def __pow__(self, n, modulo = None, context=None): """Return self ** n (mod modulo) If modulo is None (default), don't take it mod modulo. """ n = _convert_other(n) if n is NotImplemented: return n if context is None: context = getcontext() if self._is_special or n._is_special or n.adjusted() > 8: #Because the spot << doesn't work with really big exponents if n._isinfinity() or n.adjusted() > 8: return context._raise_error(InvalidOperation, 'x ** INF') ans = self._check_nans(n, context) if ans: return ans if not n._isinteger(): return context._raise_error(InvalidOperation, 'x ** (non-integer)') if not self and not n: return context._raise_error(InvalidOperation, '0 ** 0') if not n: return Decimal(1) if self == Decimal(1): return Decimal(1) sign = self._sign and not n._iseven() n = int(n) if self._isinfinity(): if modulo: return context._raise_error(InvalidOperation, 'INF % x') if n > 0: return Infsign[sign] return Decimal( (sign, (0,), 0) ) #with ludicrously large exponent, just raise an overflow and return inf. if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \ and self: tmp = Decimal('inf') tmp._sign = sign context._raise_error(Rounded) context._raise_error(Inexact) context._raise_error(Overflow, 'Big power', sign) return tmp elength = len(str(abs(n))) firstprec = context.prec if not modulo and firstprec + elength + 1 > DefaultContext.Emax: return context._raise_error(Overflow, 'Too much precision.', sign) mul = Decimal(self) val = Decimal(1) context = context._shallow_copy() context.prec = firstprec + elength + 1 if n < 0: #n is a long now, not Decimal instance n = -n mul = Decimal(1).__div__(mul, context=context) spot = 1 while spot <= n: spot <<= 1 spot >>= 1 #Spot is the highest power of 2 less than n while spot: val = val.__mul__(val, context=context) if val._isinfinity(): val = Infsign[sign] break if spot & n: val = val.__mul__(mul, context=context) if modulo is not None: val = val.__mod__(modulo, context=context) spot >>= 1 context.prec = firstprec if context._rounding_decision == ALWAYS_ROUND: return val._fix(context) return val def __rpow__(self, other, context=None): """Swaps self/other and returns __pow__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__pow__(self, context=context) def normalize(self, context=None): """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" if self._is_special: ans = self._check_nans(context=context) if ans: return ans dup = self._fix(context) if dup._isinfinity(): return dup if not dup: return Decimal( (dup._sign, (0,), 0) ) end = len(dup._int) exp = dup._exp while dup._int[end-1] == 0: exp += 1 end -= 1 return Decimal( (dup._sign, dup._int[:end], exp) ) def quantize(self, exp, rounding=None, context=None, watchexp=1): """Quantize self so its exponent is the same as that of exp. Similar to self._rescale(exp._exp) but with error checking. """ if self._is_special or exp._is_special: ans = self._check_nans(exp, context) if ans: return ans if exp._isinfinity() or self._isinfinity(): if exp._isinfinity() and self._isinfinity(): return self #if both are inf, it is OK if context is None: context = getcontext() return context._raise_error(InvalidOperation, 'quantize with one INF') return self._rescale(exp._exp, rounding, context, watchexp) def same_quantum(self, other): """Test whether self and other have the same exponent. same as self._exp == other._exp, except NaN == sNaN """ if self._is_special or other._is_special: if self._isnan() or other._isnan(): return self._isnan() and other._isnan() and True if self._isinfinity() or other._isinfinity(): return self._isinfinity() and other._isinfinity() and True return self._exp == other._exp def _rescale(self, exp, rounding=None, context=None, watchexp=1): """Rescales so that the exponent is exp. exp = exp to scale to (an integer) rounding = rounding version watchexp: if set (default) an error is returned if exp is greater than Emax or less than Etiny. """ if context is None: context = getcontext() if self._is_special: if self._isinfinity(): return context._raise_error(InvalidOperation, 'rescale with an INF') ans = self._check_nans(context=context) if ans: return ans if watchexp and (context.Emax < exp or context.Etiny() > exp): return context._raise_error(InvalidOperation, 'rescale(a, INF)') if not self: ans = Decimal(self) ans._int = (0,) ans._exp = exp return ans diff = self._exp - exp digits = len(self._int) + diff if watchexp and digits > context.prec: return context._raise_error(InvalidOperation, 'Rescale > prec') tmp = Decimal(self) tmp._int = (0,) + tmp._int digits += 1 if digits < 0: tmp._exp = -digits + tmp._exp tmp._int = (0,1) digits = 1 tmp = tmp._round(digits, rounding, context=context) if tmp._int[0] == 0 and len(tmp._int) > 1: tmp._int = tmp._int[1:] tmp._exp = exp tmp_adjusted = tmp.adjusted() if tmp and tmp_adjusted < context.Emin: context._raise_error(Subnormal) elif tmp and tmp_adjusted > context.Emax: return context._raise_error(InvalidOperation, 'rescale(a, INF)') return tmp def to_integral(self, rounding=None, context=None): """Rounds to the nearest integer, without raising inexact, rounded.""" if self._is_special: ans = self._check_nans(context=context) if ans: return ans return self if self._exp >= 0: return self if context is None: context = getcontext() flags = context._ignore_flags(Rounded, Inexact) ans = self._rescale(0, rounding, context=context) context._regard_flags(flags) return ans def sqrt(self, context=None): """Return the square root of self. Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) Should quadratically approach the right answer. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() and self._sign == 0: return Decimal(self) if not self: #exponent = self._exp / 2, using round_down. #if self._exp < 0: # exp = (self._exp+1) // 2 #else: exp = (self._exp) // 2 if self._sign == 1: #sqrt(-0) = -0 return Decimal( (1, (0,), exp)) else: return Decimal( (0, (0,), exp)) if context is None: context = getcontext() if self._sign == 1: return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') tmp = Decimal(self) expadd = tmp._exp // 2 if tmp._exp & 1: tmp._int += (0,) tmp._exp = 0 else: tmp._exp = 0 context = context._shallow_copy() flags = context._ignore_all_flags() firstprec = context.prec context.prec = 3 if tmp.adjusted() & 1 == 0: ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) ) ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)), context=context), context=context) ans._exp -= 1 + tmp.adjusted() // 2 else: ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) ) ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)), context=context), context=context) ans._exp -= 1 + tmp.adjusted() // 2 #ans is now a linear approximation. Emax, Emin = context.Emax, context.Emin context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin half = Decimal('0.5') maxp = firstprec + 2 rounding = context._set_rounding(ROUND_HALF_EVEN) while 1: context.prec = min(2*context.prec - 2, maxp) ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context), context=context), context=context) if context.prec == maxp: break #round to the answer's precision-- the only error can be 1 ulp. context.prec = firstprec prevexp = ans.adjusted() ans = ans._round(context=context) #Now, check if the other last digits are better. context.prec = firstprec + 1 # In case we rounded up another digit and we should actually go lower. if prevexp != ans.adjusted(): ans._int += (0,) ans._exp -= 1 lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context) context._set_rounding(ROUND_UP) if lower.__mul__(lower, context=context) > (tmp): ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context) else: upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context) context._set_rounding(ROUND_DOWN) if upper.__mul__(upper, context=context) < tmp: ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context) ans._exp += expadd context.prec = firstprec context.rounding = rounding ans = ans._fix(context) rounding = context._set_rounding_decision(NEVER_ROUND) if not ans.__mul__(ans, context=context) == self: # Only rounded/inexact if here. context._regard_flags(flags) context._raise_error(Rounded) context._raise_error(Inexact) else: #Exact answer, so let's set the exponent right. #if self._exp < 0: # exp = (self._exp +1)// 2 #else: exp = self._exp // 2 context.prec += ans._exp - exp ans = ans._rescale(exp, context=context) context.prec = firstprec context._regard_flags(flags) context.Emax, context.Emin = Emax, Emin return ans._fix(context) def max(self, other, context=None): """Returns the larger value. like max(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: # if one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context) ans = self c = self.__cmp__(other) if c == 0: # if both operands are finite and equal in numerical value # then an ordering is applied: # # if the signs differ then max returns the operand with the # positive sign and min returns the operand with the negative sign # # if the signs are the same then the exponent is used to select # the result. if self._sign != other._sign: if self._sign: ans = other elif self._exp < other._exp and not self._sign: ans = other elif self._exp > other._exp and self._sign: ans = other elif c == -1: ans = other if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans def min(self, other, context=None): """Returns the smaller value. like min(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: # if one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context) ans = self c = self.__cmp__(other) if c == 0: # if both operands are finite and equal in numerical value # then an ordering is applied: # # if the signs differ then max returns the operand with the # positive sign and min returns the operand with the negative sign # # if the signs are the same then the exponent is used to select # the result. if self._sign != other._sign: if other._sign: ans = other elif self._exp > other._exp and not self._sign: ans = other elif self._exp < other._exp and self._sign: ans = other elif c == 1: ans = other if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans def _isinteger(self): """Returns whether self is an integer""" if self._exp >= 0: return True rest = self._int[self._exp:] return rest == (0,)*len(rest) def _iseven(self): """Returns 1 if self is even. Assumes self is an integer.""" if self._exp > 0: return 1 return self._int[-1+self._exp] & 1 == 0 def adjusted(self): """Return the adjusted exponent of self""" try: return self._exp + len(self._int) - 1 #If NaN or Infinity, self._exp is string except TypeError: return 0 # support for pickling, copy, and deepcopy def __reduce__(self): return (self.__class__, (str(self),)) def __copy__(self): if type(self) == Decimal: return self # I'm immutable; therefore I am my own clone return self.__class__(str(self)) def __deepcopy__(self, memo): if type(self) == Decimal: return self # My components are also immutable return self.__class__(str(self)) ##### Context class ########################################### # get rounding method function: rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')] for name in rounding_functions: #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value. globalname = name[1:].upper() val = globals()[globalname] Decimal._pick_rounding_function[val] = name del name, val, globalname, rounding_functions class Context(object): """Contains the context for a Decimal instance. Contains: prec - precision (for use in rounding, division, square roots..) rounding - rounding type. (how you round) _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round? traps - If traps[exception] = 1, then the exception is raised when it is caused. Otherwise, a value is substituted in. flags - When an exception is caused, flags[exception] is incremented. (Whether or not the trap_enabler is set) Should be reset by user of Decimal instance. Emin - Minimum exponent Emax - Maximum exponent capitals - If 1, 1*10^1 is printed as 1E+1. If 0, printed as 1e1 _clamp - If 1, change exponents if too high (Default 0) """ def __init__(self, prec=None, rounding=None, traps=None, flags=None, _rounding_decision=None, Emin=None, Emax=None, capitals=None, _clamp=0, _ignored_flags=None): if flags is None: flags = [] if _ignored_flags is None: _ignored_flags = [] if not isinstance(flags, dict): flags = dict([(s,s in flags) for s in _signals]) del s if traps is not None and not isinstance(traps, dict): traps = dict([(s,s in traps) for s in _signals]) del s for name, val in locals().items(): if val is None: setattr(self, name, copy.copy(getattr(DefaultContext, name))) else: setattr(self, name, val) del self.self def __repr__(self): """Show the current context.""" s = [] s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self)) s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']') s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']') return ', '.join(s) + ')' def clear_flags(self): """Reset all flags to zero""" for flag in self.flags: self.flags[flag] = 0 def _shallow_copy(self): """Returns a shallow copy from self.""" nc = Context(self.prec, self.rounding, self.traps, self.flags, self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags) return nc def copy(self): """Returns a deep copy from self.""" nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags) return nc __copy__ = copy def _raise_error(self, condition, explanation = None, *args): """Handles an error If the flag is in _ignored_flags, returns the default response. Otherwise, it increments the flag, then, if the corresponding trap_enabler is set, it reaises the exception. Otherwise, it returns the default value after incrementing the flag. """ error = _condition_map.get(condition, condition) if error in self._ignored_flags: #Don't touch the flag return error().handle(self, *args) self.flags[error] += 1 if not self.traps[error]: #The errors define how to handle themselves. return condition().handle(self, *args) # Errors should only be risked on copies of the context #self._ignored_flags = [] raise error, explanation def _ignore_all_flags(self): """Ignore all flags, if they are raised""" return self._ignore_flags(*_signals) def _ignore_flags(self, *flags): """Ignore the flags, if they are raised""" # Do not mutate-- This way, copies of a context leave the original # alone. self._ignored_flags = (self._ignored_flags + list(flags)) return list(flags) def _regard_flags(self, *flags): """Stop ignoring the flags, if they are raised""" if flags and isinstance(flags[0], (tuple,list)): flags = flags[0] for flag in flags: self._ignored_flags.remove(flag) def __hash__(self): """A Context cannot be hashed.""" # We inherit object.__hash__, so we must deny this explicitly raise TypeError, "Cannot hash a Context." def Etiny(self): """Returns Etiny (= Emin - prec + 1)""" return int(self.Emin - self.prec + 1) def Etop(self): """Returns maximum exponent (= Emax - prec + 1)""" return int(self.Emax - self.prec + 1) def _set_rounding_decision(self, type): """Sets the rounding decision. Sets the rounding decision, and returns the current (previous) rounding decision. Often used like: context = context._shallow_copy() # That so you don't change the calling context # if an error occurs in the middle (say DivisionImpossible is raised). rounding = context._set_rounding_decision(NEVER_ROUND) instance = instance / Decimal(2) context._set_rounding_decision(rounding) This will make it not round for that operation. """ rounding = self._rounding_decision self._rounding_decision = type return rounding def _set_rounding(self, type): """Sets the rounding type. Sets the rounding type, and returns the current (previous) rounding type. Often used like: context = context.copy() # so you don't change the calling context # if an error occurs in the middle. rounding = context._set_rounding(ROUND_UP) val = self.__sub__(other, context=context) context._set_rounding(rounding) This will make it round up for that operation. """ rounding = self.rounding self.rounding= type return rounding def create_decimal(self, num='0'): """Creates a new Decimal instance but using self as context.""" d = Decimal(num, context=self) return d._fix(self) #Methods def abs(self, a): """Returns the absolute value of the operand. If the operand is negative, the result is the same as using the minus operation on the operand. Otherwise, the result is the same as using the plus operation on the operand. >>> ExtendedContext.abs(Decimal('2.1')) Decimal("2.1") >>> ExtendedContext.abs(Decimal('-100')) Decimal("100") >>> ExtendedContext.abs(Decimal('101.5')) Decimal("101.5") >>> ExtendedContext.abs(Decimal('-101.5')) Decimal("101.5") """ return a.__abs__(context=self) def add(self, a, b): """Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal("19.00") >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal("1.02E+4") """ return a.__add__(b, context=self) def _apply(self, a): return str(a._fix(self)) def compare(self, a, b): """Compares values numerically. If the signs of the operands differ, a value representing each operand ('-1' if the operand is less than zero, '0' if the operand is zero or negative zero, or '1' if the operand is greater than zero) is used in place of that operand for the comparison instead of the actual operand. The comparison is then effected by subtracting the second operand from the first and then returning a value according to the result of the subtraction: '-1' if the result is less than zero, '0' if the result is zero or negative zero, or '1' if the result is greater than zero. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) Decimal("-1") >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) Decimal("0") >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) Decimal("0") >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) Decimal("1") >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) Decimal("1") >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) Decimal("-1") """ return a.compare(b, context=self) def divide(self, a, b): """Decimal division in a specified context. >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) Decimal("0.333333333") >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) Decimal("0.666666667") >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) Decimal("2.5") >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) Decimal("0.1") >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) Decimal("1") >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) Decimal("4.00") >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) Decimal("1.20") >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) Decimal("10") >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) Decimal("1000") >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) Decimal("1.20E+6") """ return a.__div__(b, context=self) def divide_int(self, a, b): """Divides two numbers and returns the integer part of the result. >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) Decimal("0") >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) Decimal("3") >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) Decimal("3") """ return a.__floordiv__(b, context=self) def divmod(self, a, b): return a.__divmod__(b, context=self) def max(self, a,b): """max compares two values numerically and returns the maximum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the maximum (closer to positive infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal('3'), Decimal('2')) Decimal("3") >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) Decimal("3") >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) Decimal("1") >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) Decimal("7") """ return a.max(b, context=self) def min(self, a,b): """min compares two values numerically and returns the minimum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the minimum (closer to negative infinity) of the two operands is chosen as the result. >>> ExtendedContext.min(Decimal('3'), Decimal('2')) Decimal("2") >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) Decimal("-10") >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) Decimal("1.0") >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) Decimal("7") """ return a.min(b, context=self) def minus(self, a): """Minus corresponds to unary prefix minus in Python. The operation is evaluated using the same rules as subtract; the operation minus(a) is calculated as subtract('0', a) where the '0' has the same exponent as the operand. >>> ExtendedContext.minus(Decimal('1.3')) Decimal("-1.3") >>> ExtendedContext.minus(Decimal('-1.3')) Decimal("1.3") """ return a.__neg__(context=self) def multiply(self, a, b): """multiply multiplies two operands. If either operand is a special value then the general rules apply. Otherwise, the operands are multiplied together ('long multiplication'), resulting in a number which may be as long as the sum of the lengths of the two operands. >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) Decimal("3.60") >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) Decimal("21") >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) Decimal("0.72") >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) Decimal("-0.0") >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) Decimal("4.28135971E+11") """ return a.__mul__(b, context=self) def normalize(self, a): """normalize reduces an operand to its simplest form. Essentially a plus operation with all trailing zeros removed from the result. >>> ExtendedContext.normalize(Decimal('2.1')) Decimal("2.1") >>> ExtendedContext.normalize(Decimal('-2.0')) Decimal("-2") >>> ExtendedContext.normalize(Decimal('1.200')) Decimal("1.2") >>> ExtendedContext.normalize(Decimal('-120')) Decimal("-1.2E+2") >>> ExtendedContext.normalize(Decimal('120.00')) Decimal("1.2E+2") >>> ExtendedContext.normalize(Decimal('0.00')) Decimal("0") """ return a.normalize(context=self) def plus(self, a): """Plus corresponds to unary prefix plus in Python. The operation is evaluated using the same rules as add; the operation plus(a) is calculated as add('0', a) where the '0' has the same exponent as the operand. >>> ExtendedContext.plus(Decimal('1.3')) Decimal("1.3") >>> ExtendedContext.plus(Decimal('-1.3')) Decimal("-1.3") """ return a.__pos__(context=self) def power(self, a, b, modulo=None): """Raises a to the power of b, to modulo if given. The right-hand operand must be a whole number whose integer part (after any exponent has been applied) has no more than 9 digits and whose fractional part (if any) is all zeros before any rounding. The operand may be positive, negative, or zero; if negative, the absolute value of the power is used, and the left-hand operand is inverted (divided into 1) before use. If the increased precision needed for the intermediate calculations exceeds the capabilities of the implementation then an Invalid operation condition is raised. If, when raising to a negative power, an underflow occurs during the division into 1, the operation is not halted at that point but continues. >>> ExtendedContext.power(Decimal('2'), Decimal('3')) Decimal("8") >>> ExtendedContext.power(Decimal('2'), Decimal('-3')) Decimal("0.125") >>> ExtendedContext.power(Decimal('1.7'), Decimal('8')) Decimal("69.7575744") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2')) Decimal("0") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1')) Decimal("0") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0')) Decimal("1") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1')) Decimal("Infinity") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2')) Decimal("Infinity") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2')) Decimal("0") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1')) Decimal("-0") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0')) Decimal("1") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1')) Decimal("-Infinity") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2')) Decimal("Infinity") >>> ExtendedContext.power(Decimal('0'), Decimal('0')) Decimal("NaN") """ return a.__pow__(b, modulo, context=self) def quantize(self, a, b): """Returns a value equal to 'a' (rounded) and having the exponent of 'b'. The coefficient of the result is derived from that of the left-hand operand. It may be rounded using the current rounding setting (if the exponent is being increased), multiplied by a positive power of ten (if the exponent is being decreased), or is unchanged (if the exponent is already equal to that of the right-hand operand). Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision then an Invalid operation condition is raised. This guarantees that, unless there is an error condition, the exponent of the result of a quantize is always equal to that of the right-hand operand. Also unlike other operations, quantize will never raise Underflow, even if the result is subnormal and inexact. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) Decimal("2.170") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) Decimal("2.17") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) Decimal("2.2") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) Decimal("2") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) Decimal("0E+1") >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) Decimal("-Infinity") >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) Decimal("NaN") >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) Decimal("-0") >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) Decimal("-0E+5") >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) Decimal("NaN") >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) Decimal("NaN") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) Decimal("217.0") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) Decimal("217") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) Decimal("2.2E+2") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) Decimal("2E+2") """ return a.quantize(b, context=self) def remainder(self, a, b): """Returns the remainder from integer division. The result is the residue of the dividend after the operation of calculating integer division as described for divide-integer, rounded to precision digits if necessary. The sign of the result, if non-zero, is the same as that of the original dividend. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) Decimal("2.1") >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) Decimal("1") >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) Decimal("-1") >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) Decimal("0.2") >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) Decimal("0.1") >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) Decimal("1.0") """ return a.__mod__(b, context=self) def remainder_near(self, a, b): """Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal("-0.9") >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal("-2") >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal("1") >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal("-1") >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal("0.2") >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal("0.1") >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal("-0.3") """ return a.remainder_near(b, context=self) def same_quantum(self, a, b): """Returns True if the two operands have the same exponent. The result is never affected by either the sign or the coefficient of either operand. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) False >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) True >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) False >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) True """ return a.same_quantum(b) def sqrt(self, a): """Returns the square root of a non-negative number to context precision. If the result must be inexact, it is rounded using the round-half-even algorithm. >>> ExtendedContext.sqrt(Decimal('0')) Decimal("0") >>> ExtendedContext.sqrt(Decimal('-0')) Decimal("-0") >>> ExtendedContext.sqrt(Decimal('0.39')) Decimal("0.624499800") >>> ExtendedContext.sqrt(Decimal('100')) Decimal("10") >>> ExtendedContext.sqrt(Decimal('1')) Decimal("1") >>> ExtendedContext.sqrt(Decimal('1.0')) Decimal("1.0") >>> ExtendedContext.sqrt(Decimal('1.00')) Decimal("1.0") >>> ExtendedContext.sqrt(Decimal('7')) Decimal("2.64575131") >>> ExtendedContext.sqrt(Decimal('10')) Decimal("3.16227766") >>> ExtendedContext.prec 9 """ return a.sqrt(context=self) def subtract(self, a, b): """Return the sum of the two operands. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) Decimal("0.23") >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) Decimal("0.00") >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) Decimal("-0.77") """ return a.__sub__(b, context=self) def to_eng_string(self, a): """Converts a number to a string, using scientific notation. The operation is not affected by the context. """ return a.to_eng_string(context=self) def to_sci_string(self, a): """Converts a number to a string, using scientific notation. The operation is not affected by the context. """ return a.__str__(context=self) def to_integral(self, a): """Rounds to an integer. When the operand has a negative exponent, the result is the same as using the quantize() operation using the given operand as the left-hand-operand, 1E+0 as the right-hand-operand, and the precision of the operand as the precision setting, except that no flags will be set. The rounding mode is taken from the context. >>> ExtendedContext.to_integral(Decimal('2.1')) Decimal("2") >>> ExtendedContext.to_integral(Decimal('100')) Decimal("100") >>> ExtendedContext.to_integral(Decimal('100.0')) Decimal("100") >>> ExtendedContext.to_integral(Decimal('101.5')) Decimal("102") >>> ExtendedContext.to_integral(Decimal('-101.5')) Decimal("-102") >>> ExtendedContext.to_integral(Decimal('10E+5')) Decimal("1.0E+6") >>> ExtendedContext.to_integral(Decimal('7.89E+77')) Decimal("7.89E+77") >>> ExtendedContext.to_integral(Decimal('-Inf')) Decimal("-Infinity") """ return a.to_integral(context=self) class _WorkRep(object): __slots__ = ('sign','int','exp') # sign: 0 or 1 # int: int or long # exp: None, int, or string def __init__(self, value=None): if value is None: self.sign = None self.int = 0 self.exp = None elif isinstance(value, Decimal): self.sign = value._sign cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum self.exp = value._exp else: # assert isinstance(value, tuple) self.sign = value[0] self.int = value[1] self.exp = value[2] def __repr__(self): return "(%r, %r, %r)" % (self.sign, self.int, self.exp) __str__ = __repr__ def _normalize(op1, op2, shouldround = 0, prec = 0): """Normalizes op1, op2 to have the same exp and length of coefficient. Done during addition. """ # Yes, the exponent is a long, but the difference between exponents # must be an int-- otherwise you'd get a big memory problem. numdigits = int(op1.exp - op2.exp) if numdigits < 0: numdigits = -numdigits tmp = op2 other = op1 else: tmp = op1 other = op2 if shouldround and numdigits > prec + 1: # Big difference in exponents - check the adjusted exponents tmp_len = len(str(tmp.int)) other_len = len(str(other.int)) if numdigits > (other_len + prec + 1 - tmp_len): # If the difference in adjusted exps is > prec+1, we know # other is insignificant, so might as well put a 1 after the precision. # (since this is only for addition.) Also stops use of massive longs. extend = prec + 2 - tmp_len if extend <= 0: extend = 1 tmp.int *= 10 ** extend tmp.exp -= extend other.int = 1 other.exp = tmp.exp return op1, op2 tmp.int *= 10 ** numdigits tmp.exp -= numdigits return op1, op2 def _adjust_coefficients(op1, op2): """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int. Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. Used on _WorkRep instances during division. """ adjust = 0 #If op1 is smaller, make it larger while op2.int > op1.int: op1.int *= 10 op1.exp -= 1 adjust += 1 #If op2 is too small, make it larger while op1.int >= (10 * op2.int): op2.int *= 10 op2.exp -= 1 adjust -= 1 return op1, op2, adjust ##### Helper Functions ######################################## def _convert_other(other): """Convert other to Decimal. Verifies that it's ok to use in an implicit construction. """ if isinstance(other, Decimal): return other if isinstance(other, (int, long)): return Decimal(other) return NotImplemented _infinity_map = { 'inf' : 1, 'infinity' : 1, '+inf' : 1, '+infinity' : 1, '-inf' : -1, '-infinity' : -1 } def _isinfinity(num): """Determines whether a string or float is infinity. +1 for negative infinity; 0 for finite ; +1 for positive infinity """ num = str(num).lower() return _infinity_map.get(num, 0) def _isnan(num): """Determines whether a string or float is NaN (1, sign, diagnostic info as string) => NaN (2, sign, diagnostic info as string) => sNaN 0 => not a NaN """ num = str(num).lower() if not num: return 0 #get the sign, get rid of trailing [+-] sign = 0 if num[0] == '+': num = num[1:] elif num[0] == '-': #elif avoids '+-nan' num = num[1:] sign = 1 if num.startswith('nan'): if len(num) > 3 and not num[3:].isdigit(): #diagnostic info return 0 return (1, sign, num[3:].lstrip('0')) if num.startswith('snan'): if len(num) > 4 and not num[4:].isdigit(): return 0 return (2, sign, num[4:].lstrip('0')) return 0 ##### Setup Specific Contexts ################################ # The default context prototype used by Context() # Is mutable, so that new contexts can have different default values DefaultContext = Context( prec=28, rounding=ROUND_HALF_EVEN, traps=[DivisionByZero, Overflow, InvalidOperation], flags=[], _rounding_decision=ALWAYS_ROUND, Emax=999999999, Emin=-999999999, capitals=1 ) # Pre-made alternate contexts offered by the specification # Don't change these; the user should be able to select these # contexts and be able to reproduce results from other implementations # of the spec. BasicContext = Context( prec=9, rounding=ROUND_HALF_UP, traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], flags=[], ) ExtendedContext = Context( prec=9, rounding=ROUND_HALF_EVEN, traps=[], flags=[], ) ##### Useful Constants (internal use only) #################### #Reusable defaults Inf = Decimal('Inf') negInf = Decimal('-Inf') #Infsign[sign] is infinity w/ that sign Infsign = (Inf, negInf) NaN = Decimal('NaN') ##### crud for parsing strings ################################# import re # There's an optional sign at the start, and an optional exponent # at the end. The exponent has an optional sign and at least one # digit. In between, must have either at least one digit followed # by an optional fraction, or a decimal point followed by at least # one digit. Yuck. _parser = re.compile(r""" # \s* (?P<sign>[-+])? ( (?P<int>\d+) (\. (?P<frac>\d*))? | \. (?P<onlyfrac>\d+) ) ([eE](?P<exp>[-+]? \d+))? # \s* $ """, re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces. del re # return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly def _string2exact(s): m = _parser(s) if m is None: raise ValueError("invalid literal for Decimal: %r" % s) if m.group('sign') == "-": sign = 1 else: sign = 0 exp = m.group('exp') if exp is None: exp = 0 else: exp = int(exp) intpart = m.group('int') if intpart is None: intpart = "" fracpart = m.group('onlyfrac') else: fracpart = m.group('frac') if fracpart is None: fracpart = "" exp -= len(fracpart) mantissa = intpart + fracpart tmp = map(int, mantissa) backup = tmp while tmp and tmp[0] == 0: del tmp[0] # It's a zero if not tmp: if backup: return (sign, tuple(backup), exp) return (sign, (0,), exp) mantissa = tuple(tmp) return (sign, mantissa, exp) if __name__ == '__main__': import doctest, sys doctest.testmod(sys.modules[__name__])
Python
"""Extract, format and print information about Python stack traces.""" import linecache import sys import types __all__ = ['extract_stack', 'extract_tb', 'format_exception', 'format_exception_only', 'format_list', 'format_stack', 'format_tb', 'print_exc', 'format_exc', 'print_exception', 'print_last', 'print_stack', 'print_tb', 'tb_lineno'] def _print(file, str='', terminator='\n'): file.write(str+terminator) def print_list(extracted_list, file=None): """Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.""" if file is None: file = sys.stderr for filename, lineno, name, line in extracted_list: _print(file, ' File "%s", line %d, in %s' % (filename,lineno,name)) if line: _print(file, ' %s' % line.strip()) def format_list(extracted_list): """Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. """ list = [] for filename, lineno, name, line in extracted_list: item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) if line: item = item + ' %s\n' % line.strip() list.append(item) return list def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method. """ if file is None: file = sys.stderr if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name _print(file, ' File "%s", line %d, in %s' % (filename,lineno,name)) linecache.checkcache(filename) line = linecache.getline(filename, lineno) if line: _print(file, ' ' + line.strip()) tb = tb.tb_next n = n+1 def format_tb(tb, limit = None): """A shorthand for 'format_list(extract_stack(f, limit)).""" return format_list(extract_tb(tb, limit)) def extract_tb(tb, limit = None): """Return list of up to limit pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None. """ if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit list = [] n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno) if line: line = line.strip() else: line = None list.append((filename, lineno, name, line)) tb = tb.tb_next n = n+1 return list def print_exception(etype, value, tb, limit=None, file=None): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate position of the error. """ if file is None: file = sys.stderr if tb: _print(file, 'Traceback (most recent call last):') print_tb(tb, limit, file) lines = format_exception_only(etype, value) for line in lines[:-1]: _print(file, line, ' ') _print(file, lines[-1], '') def format_exception(etype, value, tb, limit = None): """Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception(). """ if tb: list = ['Traceback (most recent call last):\n'] list = list + format_tb(tb, limit) else: list = [] list = list + format_exception_only(etype, value) return list def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. """ list = [] if isinstance(etype, (type, types.ClassType)): stype = etype.__name__ else: stype = etype if value is None: list.append(str(stype) + '\n') else: if etype is SyntaxError: try: msg, (filename, lineno, offset, line) = value except: pass else: if not filename: filename = "<string>" list.append(' File "%s", line %d\n' % (filename, lineno)) if line is not None: i = 0 while i < len(line) and line[i].isspace(): i = i+1 list.append(' %s\n' % line.strip()) if offset is not None: s = ' ' for c in line[i:offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg s = _some_str(value) if s: list.append('%s: %s\n' % (str(stype), s)) else: list.append('%s\n' % str(stype)) return list def _some_str(value): try: return str(value) except: return '<unprintable %s object>' % type(value).__name__ def print_exc(limit=None, file=None): """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way.)""" if file is None: file = sys.stderr try: etype, value, tb = sys.exc_info() print_exception(etype, value, tb, limit, file) finally: etype = value = tb = None def format_exc(limit=None): """Like print_exc() but return a string.""" try: etype, value, tb = sys.exc_info() return ''.join(format_exception(etype, value, tb, limit)) finally: etype = value = tb = None def print_last(limit=None, file=None): """This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.""" if file is None: file = sys.stderr print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file) def print_stack(f=None, limit=None, file=None): """Print a stack trace from its invocation point. The optional 'f' argument can be used to specify an alternate stack frame at which to start. The optional 'limit' and 'file' arguments have the same meaning as for print_exception(). """ if f is None: try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame.f_back print_list(extract_stack(f, limit), file) def format_stack(f=None, limit=None): """Shorthand for 'format_list(extract_stack(f, limit))'.""" if f is None: try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame.f_back return format_list(extract_stack(f, limit)) def extract_stack(f=None, limit = None): """Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for print_stack(). Each item in the list is a quadruple (filename, line number, function name, text), and the entries are in order from oldest to newest stack frame. """ if f is None: try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame.f_back if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit list = [] n = 0 while f is not None and (limit is None or n < limit): lineno = f.f_lineno co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno) if line: line = line.strip() else: line = None list.append((filename, lineno, name, line)) f = f.f_back n = n+1 list.reverse() return list def tb_lineno(tb): """Calculate correct line number of traceback given in tb. Obsolete in 2.3. """ return tb.tb_lineno
Python
"""Macintosh binhex compression/decompression. easy interface: binhex(inputfilename, outputfilename) hexbin(inputfilename, outputfilename) """ # # Jack Jansen, CWI, August 1995. # # The module is supposed to be as compatible as possible. Especially the # easy interface should work "as expected" on any platform. # XXXX Note: currently, textfiles appear in mac-form on all platforms. # We seem to lack a simple character-translate in python. # (we should probably use ISO-Latin-1 on all but the mac platform). # XXXX The simple routines are too simple: they expect to hold the complete # files in-core. Should be fixed. # XXXX It would be nice to handle AppleDouble format on unix # (for servers serving macs). # XXXX I don't understand what happens when you get 0x90 times the same byte on # input. The resulting code (xx 90 90) would appear to be interpreted as an # escaped *value* of 0x90. All coders I've seen appear to ignore this nicety... # import sys import os import struct import binascii __all__ = ["binhex","hexbin","Error"] class Error(Exception): pass # States (what have we written) [_DID_HEADER, _DID_DATA, _DID_RSRC] = range(3) # Various constants REASONABLY_LARGE=32768 # Minimal amount we pass the rle-coder LINELEN=64 RUNCHAR=chr(0x90) # run-length introducer # # This code is no longer byte-order dependent # # Workarounds for non-mac machines. if os.name == 'mac': import macfs import MacOS try: openrf = MacOS.openrf except AttributeError: # Backward compatibility openrf = open def FInfo(): return macfs.FInfo() def getfileinfo(name): finfo = macfs.FSSpec(name).GetFInfo() dir, file = os.path.split(name) # XXXX Get resource/data sizes fp = open(name, 'rb') fp.seek(0, 2) dlen = fp.tell() fp = openrf(name, '*rb') fp.seek(0, 2) rlen = fp.tell() return file, finfo, dlen, rlen def openrsrc(name, *mode): if not mode: mode = '*rb' else: mode = '*' + mode[0] return openrf(name, mode) else: # # Glue code for non-macintosh usage # class FInfo: def __init__(self): self.Type = '????' self.Creator = '????' self.Flags = 0 def getfileinfo(name): finfo = FInfo() # Quick check for textfile fp = open(name) data = open(name).read(256) for c in data: if not c.isspace() and (c<' ' or ord(c) > 0x7f): break else: finfo.Type = 'TEXT' fp.seek(0, 2) dsize = fp.tell() fp.close() dir, file = os.path.split(name) file = file.replace(':', '-', 1) return file, finfo, dsize, 0 class openrsrc: def __init__(self, *args): pass def read(self, *args): return '' def write(self, *args): pass def close(self): pass class _Hqxcoderengine: """Write data to the coder in 3-byte chunks""" def __init__(self, ofp): self.ofp = ofp self.data = '' self.hqxdata = '' self.linelen = LINELEN-1 def write(self, data): self.data = self.data + data datalen = len(self.data) todo = (datalen//3)*3 data = self.data[:todo] self.data = self.data[todo:] if not data: return self.hqxdata = self.hqxdata + binascii.b2a_hqx(data) self._flush(0) def _flush(self, force): first = 0 while first <= len(self.hqxdata)-self.linelen: last = first + self.linelen self.ofp.write(self.hqxdata[first:last]+'\n') self.linelen = LINELEN first = last self.hqxdata = self.hqxdata[first:] if force: self.ofp.write(self.hqxdata + ':\n') def close(self): if self.data: self.hqxdata = \ self.hqxdata + binascii.b2a_hqx(self.data) self._flush(1) self.ofp.close() del self.ofp class _Rlecoderengine: """Write data to the RLE-coder in suitably large chunks""" def __init__(self, ofp): self.ofp = ofp self.data = '' def write(self, data): self.data = self.data + data if len(self.data) < REASONABLY_LARGE: return rledata = binascii.rlecode_hqx(self.data) self.ofp.write(rledata) self.data = '' def close(self): if self.data: rledata = binascii.rlecode_hqx(self.data) self.ofp.write(rledata) self.ofp.close() del self.ofp class BinHex: def __init__(self, (name, finfo, dlen, rlen), ofp): if type(ofp) == type(''): ofname = ofp ofp = open(ofname, 'w') if os.name == 'mac': fss = macfs.FSSpec(ofname) fss.SetCreatorType('BnHq', 'TEXT') ofp.write('(This file must be converted with BinHex 4.0)\n\n:') hqxer = _Hqxcoderengine(ofp) self.ofp = _Rlecoderengine(hqxer) self.crc = 0 if finfo is None: finfo = FInfo() self.dlen = dlen self.rlen = rlen self._writeinfo(name, finfo) self.state = _DID_HEADER def _writeinfo(self, name, finfo): nl = len(name) if nl > 63: raise Error, 'Filename too long' d = chr(nl) + name + '\0' d2 = finfo.Type + finfo.Creator # Force all structs to be packed with big-endian d3 = struct.pack('>h', finfo.Flags) d4 = struct.pack('>ii', self.dlen, self.rlen) info = d + d2 + d3 + d4 self._write(info) self._writecrc() def _write(self, data): self.crc = binascii.crc_hqx(data, self.crc) self.ofp.write(data) def _writecrc(self): # XXXX Should this be here?? # self.crc = binascii.crc_hqx('\0\0', self.crc) self.ofp.write(struct.pack('>H', self.crc)) self.crc = 0 def write(self, data): if self.state != _DID_HEADER: raise Error, 'Writing data at the wrong time' self.dlen = self.dlen - len(data) self._write(data) def close_data(self): if self.dlen != 0: raise Error, 'Incorrect data size, diff=%r' % (self.rlen,) self._writecrc() self.state = _DID_DATA def write_rsrc(self, data): if self.state < _DID_DATA: self.close_data() if self.state != _DID_DATA: raise Error, 'Writing resource data at the wrong time' self.rlen = self.rlen - len(data) self._write(data) def close(self): if self.state < _DID_DATA: self.close_data() if self.state != _DID_DATA: raise Error, 'Close at the wrong time' if self.rlen != 0: raise Error, \ "Incorrect resource-datasize, diff=%r" % (self.rlen,) self._writecrc() self.ofp.close() self.state = None del self.ofp def binhex(inp, out): """(infilename, outfilename) - Create binhex-encoded copy of a file""" finfo = getfileinfo(inp) ofp = BinHex(finfo, out) ifp = open(inp, 'rb') # XXXX Do textfile translation on non-mac systems while 1: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close_data() ifp.close() ifp = openrsrc(inp, 'rb') while 1: d = ifp.read(128000) if not d: break ofp.write_rsrc(d) ofp.close() ifp.close() class _Hqxdecoderengine: """Read data via the decoder in 4-byte chunks""" def __init__(self, ifp): self.ifp = ifp self.eof = 0 def read(self, totalwtd): """Read at least wtd bytes (or until EOF)""" decdata = '' wtd = totalwtd # # The loop here is convoluted, since we don't really now how # much to decode: there may be newlines in the incoming data. while wtd > 0: if self.eof: return decdata wtd = ((wtd+2)//3)*4 data = self.ifp.read(wtd) # # Next problem: there may not be a complete number of # bytes in what we pass to a2b. Solve by yet another # loop. # while 1: try: decdatacur, self.eof = \ binascii.a2b_hqx(data) break except binascii.Incomplete: pass newdata = self.ifp.read(1) if not newdata: raise Error, \ 'Premature EOF on binhex file' data = data + newdata decdata = decdata + decdatacur wtd = totalwtd - len(decdata) if not decdata and not self.eof: raise Error, 'Premature EOF on binhex file' return decdata def close(self): self.ifp.close() class _Rledecoderengine: """Read data via the RLE-coder""" def __init__(self, ifp): self.ifp = ifp self.pre_buffer = '' self.post_buffer = '' self.eof = 0 def read(self, wtd): if wtd > len(self.post_buffer): self._fill(wtd-len(self.post_buffer)) rv = self.post_buffer[:wtd] self.post_buffer = self.post_buffer[wtd:] return rv def _fill(self, wtd): self.pre_buffer = self.pre_buffer + self.ifp.read(wtd+4) if self.ifp.eof: self.post_buffer = self.post_buffer + \ binascii.rledecode_hqx(self.pre_buffer) self.pre_buffer = '' return # # Obfuscated code ahead. We have to take care that we don't # end up with an orphaned RUNCHAR later on. So, we keep a couple # of bytes in the buffer, depending on what the end of # the buffer looks like: # '\220\0\220' - Keep 3 bytes: repeated \220 (escaped as \220\0) # '?\220' - Keep 2 bytes: repeated something-else # '\220\0' - Escaped \220: Keep 2 bytes. # '?\220?' - Complete repeat sequence: decode all # otherwise: keep 1 byte. # mark = len(self.pre_buffer) if self.pre_buffer[-3:] == RUNCHAR + '\0' + RUNCHAR: mark = mark - 3 elif self.pre_buffer[-1] == RUNCHAR: mark = mark - 2 elif self.pre_buffer[-2:] == RUNCHAR + '\0': mark = mark - 2 elif self.pre_buffer[-2] == RUNCHAR: pass # Decode all else: mark = mark - 1 self.post_buffer = self.post_buffer + \ binascii.rledecode_hqx(self.pre_buffer[:mark]) self.pre_buffer = self.pre_buffer[mark:] def close(self): self.ifp.close() class HexBin: def __init__(self, ifp): if type(ifp) == type(''): ifp = open(ifp) # # Find initial colon. # while 1: ch = ifp.read(1) if not ch: raise Error, "No binhex data found" # Cater for \r\n terminated lines (which show up as \n\r, hence # all lines start with \r) if ch == '\r': continue if ch == ':': break if ch != '\n': dummy = ifp.readline() hqxifp = _Hqxdecoderengine(ifp) self.ifp = _Rledecoderengine(hqxifp) self.crc = 0 self._readheader() def _read(self, len): data = self.ifp.read(len) self.crc = binascii.crc_hqx(data, self.crc) return data def _checkcrc(self): filecrc = struct.unpack('>h', self.ifp.read(2))[0] & 0xffff #self.crc = binascii.crc_hqx('\0\0', self.crc) # XXXX Is this needed?? self.crc = self.crc & 0xffff if filecrc != self.crc: raise Error, 'CRC error, computed %x, read %x' \ %(self.crc, filecrc) self.crc = 0 def _readheader(self): len = self._read(1) fname = self._read(ord(len)) rest = self._read(1+4+4+2+4+4) self._checkcrc() type = rest[1:5] creator = rest[5:9] flags = struct.unpack('>h', rest[9:11])[0] self.dlen = struct.unpack('>l', rest[11:15])[0] self.rlen = struct.unpack('>l', rest[15:19])[0] self.FName = fname self.FInfo = FInfo() self.FInfo.Creator = creator self.FInfo.Type = type self.FInfo.Flags = flags self.state = _DID_HEADER def read(self, *n): if self.state != _DID_HEADER: raise Error, 'Read data at wrong time' if n: n = n[0] n = min(n, self.dlen) else: n = self.dlen rv = '' while len(rv) < n: rv = rv + self._read(n-len(rv)) self.dlen = self.dlen - n return rv def close_data(self): if self.state != _DID_HEADER: raise Error, 'close_data at wrong time' if self.dlen: dummy = self._read(self.dlen) self._checkcrc() self.state = _DID_DATA def read_rsrc(self, *n): if self.state == _DID_HEADER: self.close_data() if self.state != _DID_DATA: raise Error, 'Read resource data at wrong time' if n: n = n[0] n = min(n, self.rlen) else: n = self.rlen self.rlen = self.rlen - n return self._read(n) def close(self): if self.rlen: dummy = self.read_rsrc(self.rlen) self._checkcrc() self.state = _DID_RSRC self.ifp.close() def hexbin(inp, out): """(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName if os.name == 'mac': ofss = macfs.FSSpec(out) out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems while 1: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close() ifp.close_data() d = ifp.read_rsrc(128000) if d: ofp = openrsrc(out, 'wb') ofp.write(d) while 1: d = ifp.read_rsrc(128000) if not d: break ofp.write(d) ofp.close() if os.name == 'mac': nfinfo = ofss.GetFInfo() nfinfo.Creator = finfo.Creator nfinfo.Type = finfo.Type nfinfo.Flags = finfo.Flags ofss.SetFInfo(nfinfo) ifp.close() def _test(): if os.name == 'mac': fss, ok = macfs.PromptGetFile('File to convert:') if not ok: sys.exit(0) fname = fss.as_pathname() else: fname = sys.argv[1] binhex(fname, fname+'.hqx') hexbin(fname+'.hqx', fname+'.viahqx') #hexbin(fname, fname+'.unpacked') sys.exit(1) if __name__ == '__main__': _test()
Python
"""A generic class to build line-oriented command interpreters. Interpreters constructed with this class obey the following conventions: 1. End of file on input is processed as the command 'EOF'. 2. A command is parsed out of each line by collecting the prefix composed of characters in the identchars member. 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method is passed a single argument consisting of the remainder of the line. 4. Typing an empty line repeats the last command. (Actually, it calls the method `emptyline', which may be overridden in a subclass.) 5. There is a predefined `help' method. Given an argument `topic', it calls the command `help_topic'. With no arguments, it lists all topics with defined help_ functions, broken into up to three topics; documented commands, miscellaneous help topics, and undocumented commands. 6. The command '?' is a synonym for `help'. The command '!' is a synonym for `shell', if a do_shell method exists. 7. If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling complete_foo() with arguments text, line, begidx, endidx. text is string we are matching against, all returned matches must begin with it. line is the current input line (lstripped), begidx and endidx are the beginning and end indexes of the text being matched, which could be used to provide different completion depending upon which position the argument is in. The `default' method may be overridden to intercept commands for which there is no do_ method. The `completedefault' method may be overridden to intercept completions for commands that have no complete_ method. The data member `self.ruler' sets the character used to draw separator lines in the help messages. If empty, no ruler line is drawn. It defaults to "=". If the value of `self.intro' is nonempty when the cmdloop method is called, it is printed out on interpreter startup. This value may be overridden via an optional argument to the cmdloop() method. The data members `self.doc_header', `self.misc_header', and `self.undoc_header' set the headers used for the help function's listings of documented functions, miscellaneous topics, and undocumented functions respectively. These interpreters use raw_input; thus, if the readline module is loaded, they automatically support Emacs-like command history and editing features. """ import string __all__ = ["Cmd"] PROMPT = '(Cmd) ' IDENTCHARS = string.ascii_letters + string.digits + '_' class Cmd: """A simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface. A Cmd instance or subclass instance is a line-oriented interpreter framework. There is no good reason to instantiate Cmd itself; rather, it's useful as a superclass of an interpreter class you define yourself in order to inherit Cmd's methods and encapsulate action methods. """ prompt = PROMPT identchars = IDENTCHARS ruler = '=' lastcmd = '' intro = None doc_leader = "" doc_header = "Documented commands (type help <topic>):" misc_header = "Miscellaneous help topics:" undoc_header = "Undocumented commands:" nohelp = "*** No help on %s" use_rawinput = 1 def __init__(self, completekey='tab', stdin=None, stdout=None): """Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used. """ import sys if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ self.preloop() if self.use_rawinput and self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") except (ImportError, AttributeError): pass try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line[:-1] # chop \n line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: if self.use_rawinput and self.completekey: try: import readline readline.set_completer(self.old_completer) except (ImportError, AttributeError): pass def precmd(self, line): """Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued. """ return line def postcmd(self, stop, line): """Hook method executed just after a command dispatch is finished.""" return stop def preloop(self): """Hook method executed once when the cmdloop() method is called.""" pass def postloop(self): """Hook method executed once when the cmdloop() method is about to return. """ pass def parseline(self, line): """Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed. """ line = line.strip() if not line: return None, None, line elif line[0] == '?': line = 'help ' + line[1:] elif line[0] == '!': if hasattr(self, 'do_shell'): line = 'shell ' + line[1:] else: return None, None, line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop. """ cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg) def emptyline(self): """Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered. """ if self.lastcmd: return self.onecmd(self.lastcmd) def default(self, line): """Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns. """ self.stdout.write('*** Unknown syntax: %s\n'%line) def completedefault(self, *ignored): """Method called to complete an input line when no command-specific complete_*() method is available. By default, it returns an empty list. """ return [] def completenames(self, text, *ignored): dotext = 'do_'+text return [a[3:] for a in self.get_names() if a.startswith(dotext)] def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None def get_names(self): # Inheritance says we have to look in class and # base classes; order is not important. names = [] classes = [self.__class__] while classes: aclass = classes.pop(0) if aclass.__bases__: classes = classes + list(aclass.__bases__) names = names + dir(aclass) return names def complete_help(self, *args): return self.completenames(*args) def do_help(self, arg): if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass self.stdout.write("%s\n"%str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write("%s\n"%str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, help.keys(),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80) def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: self.stdout.write("%s\n"%str(header)) if self.ruler: self.stdout.write("%s\n"%str(self.ruler * len(header))) self.columnize(cmds, maxcol-1) self.stdout.write("\n") def columnize(self, list, displaywidth=80): """Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough). """ if not list: self.stdout.write("<empty>\n") return nonstrings = [i for i in range(len(list)) if not isinstance(list[i], str)] if nonstrings: raise TypeError, ("list[i] not a string for i in %s" % ", ".join(map(str, nonstrings))) size = len(list) if size == 1: self.stdout.write('%s\n'%str(list[0])) return # Try every row count from 1 upwards for nrows in range(1, len(list)): ncols = (size+nrows-1) // nrows colwidths = [] totwidth = -2 for col in range(ncols): colwidth = 0 for row in range(nrows): i = row + nrows*col if i >= size: break x = list[i] colwidth = max(colwidth, len(x)) colwidths.append(colwidth) totwidth += colwidth + 2 if totwidth > displaywidth: break if totwidth <= displaywidth: break else: nrows = len(list) ncols = 1 colwidths = [0] for row in range(nrows): texts = [] for col in range(ncols): i = row + nrows*col if i >= size: x = "" else: x = list[i] texts.append(x) while texts and not texts[-1]: del texts[-1] for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) self.stdout.write("%s\n"%str(" ".join(texts)))
Python
# Wrapper module for _socket, providing some additional facilities # implemented in Python. """\ This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object. Functions: socket() -- create a new socket object socketpair() -- create a pair of new socket objects [*] fromfd() -- create a socket object from an open file descriptor [*] gethostname() -- return the current hostname gethostbyname() -- map a hostname to its IP number gethostbyaddr() -- map an IP number or hostname to DNS info getservbyname() -- map a service name and a protocol name to a port number getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order htons(), htonl() -- convert 16, 32 bit int from host to network byte order inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) ssl() -- secure socket layer support (only available if configured) socket.getdefaulttimeout() -- get the default timeout value socket.setdefaulttimeout() -- set the default timeout value [*] not available on all platforms! Special objects: SocketType -- type object for socket objects error -- exception raised for I/O errors has_ipv6 -- boolean value indicating if IPv6 is supported Integer constants: AF_INET, AF_UNIX -- socket domains (first argument to socket() call) SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) Many other constants may be defined; these may be used in calls to the setsockopt() and getsockopt() methods. """ import _socket from _socket import * _have_ssl = False try: import _ssl from _ssl import * _have_ssl = True except ImportError: pass import os, sys try: from errno import EBADF except ImportError: EBADF = 9 __all__ = ["getfqdn"] __all__.extend(os._get_exports_list(_socket)) if _have_ssl: __all__.extend(os._get_exports_list(_ssl)) _realsocket = socket if _have_ssl: _realssl = ssl def ssl(sock, keyfile=None, certfile=None): if hasattr(sock, "_sock"): sock = sock._sock return _realssl(sock, keyfile, certfile) # WSA error codes if sys.platform.lower().startswith("win"): errorTab = {} errorTab[10004] = "The operation was interrupted." errorTab[10009] = "A bad file handle was passed." errorTab[10013] = "Permission denied." errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT errorTab[10022] = "An invalid operation was attempted." errorTab[10035] = "The socket operation would block" errorTab[10036] = "A blocking operation is already in progress." errorTab[10048] = "The network address is in use." errorTab[10054] = "The connection has been reset." errorTab[10058] = "The network has been shut down." errorTab[10060] = "The operation timed out." errorTab[10061] = "Connection refused." errorTab[10063] = "The name is too long." errorTab[10064] = "The host is down." errorTab[10065] = "The host is unreachable." __all__.append("errorTab") def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname as returned by gethostname() is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name # # These classes are used by the socket() defined on Windows and BeOS # platforms to provide a best-effort implementation of the cleanup # semantics needed when sockets can't be dup()ed. # # These are not actually used on other platforms. # _socketmethods = ( 'bind', 'connect', 'connect_ex', 'fileno', 'listen', 'getpeername', 'getsockname', 'getsockopt', 'setsockopt', 'sendall', 'setblocking', 'settimeout', 'gettimeout', 'shutdown') if sys.platform == "riscos": _socketmethods = _socketmethods + ('sleeptaskw',) class _closedsocket(object): __slots__ = [] def _dummy(*args): raise error(EBADF, 'Bad file descriptor') def _drop(self): pass def _reuse(self): pass send = recv = sendto = recvfrom = __getattr__ = _dummy class _socketobject(object): __doc__ = _realsocket.__doc__ __slots__ = ["_sock", "send", "recv", "sendto", "recvfrom", "__weakref__"] def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): if _sock is None: _sock = _realsocket(family, type, proto) self._sock = _sock self.send = self._sock.send self.recv = self._sock.recv self.sendto = self._sock.sendto self.recvfrom = self._sock.recvfrom def __del__(self): self.close() def close(self): self._sock._drop() self._sock = _closedsocket() self.send = self.recv = self.sendto = self.recvfrom = self._sock._dummy close.__doc__ = _realsocket.close.__doc__ def accept(self): sock, addr = self._sock.accept() return _socketobject(_sock=sock), addr accept.__doc__ = _realsocket.accept.__doc__ def dup(self): """dup() -> socket object Return a new socket object connected to the same system resource.""" self._sock._reuse() return _socketobject(_sock=self._sock) def makefile(self, mode='r', bufsize=-1): """makefile([mode[, bufsize]]) -> file object Return a regular file object corresponding to the socket. The mode and bufsize arguments are as for the built-in open() function.""" self._sock._reuse() return _fileobject(self._sock, mode, bufsize) _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n" "%s.__doc__ = _realsocket.%s.__doc__\n") for _m in _socketmethods: exec _s % (_m, _m, _m, _m) del _m, _s socket = SocketType = _socketobject class _fileobject(object): """Faux file object attached to a socket object.""" default_bufsize = 8192 name = "<socket>" __slots__ = ["mode", "bufsize", "softspace", # "closed" is a property, see below "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"] def __init__(self, sock, mode='rb', bufsize=-1): self._sock = sock self.mode = mode # Not actually used in this version if bufsize < 0: bufsize = self.default_bufsize self.bufsize = bufsize self.softspace = False if bufsize == 0: self._rbufsize = 1 elif bufsize == 1: self._rbufsize = self.default_bufsize else: self._rbufsize = bufsize self._wbufsize = bufsize self._rbuf = "" # A string self._wbuf = [] # A list of strings def _getclosed(self): return self._sock is None closed = property(_getclosed, doc="True if the file is closed") def close(self): if self._sock: try: self.flush() finally: if self._sock: s = self._sock self._sock = None s._drop() def __del__(self): try: self.close() except: # close() may fail if __init__ didn't complete pass def flush(self): if self._wbuf: buffer = "".join(self._wbuf) self._wbuf = [] self._sock.sendall(buffer) def fileno(self): return self._sock.fileno() def write(self, data): data = str(data) # XXX Should really reject non-string non-buffers if not data: return self._wbuf.append(data) if (self._wbufsize == 0 or self._wbufsize == 1 and '\n' in data or self._get_wbuf_len() >= self._wbufsize): self.flush() def writelines(self, list): # XXX We could do better here for very long lists # XXX Should really reject non-string non-buffers self._wbuf.extend(filter(None, map(str, list))) if (self._wbufsize <= 1 or self._get_wbuf_len() >= self._wbufsize): self.flush() def _get_wbuf_len(self): buf_len = 0 for x in self._wbuf: buf_len += len(x) return buf_len def read(self, size=-1): data = self._rbuf if size < 0: # Read until EOF buffers = [] if data: buffers.append(data) self._rbuf = "" if self._rbufsize <= 1: recv_size = self.default_bufsize else: recv_size = self._rbufsize while True: data = self._sock.recv(recv_size) if not data: break buffers.append(data) return "".join(buffers) else: # Read until size bytes or EOF seen, whichever comes first buf_len = len(data) if buf_len >= size: self._rbuf = data[size:] return data[:size] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: left = size - buf_len recv_size = max(self._rbufsize, left) data = self._sock.recv(recv_size) if not data: break buffers.append(data) n = len(data) if n >= left: self._rbuf = data[left:] buffers[-1] = data[:left] break buf_len += n return "".join(buffers) def readline(self, size=-1): data = self._rbuf if size < 0: # Read until \n or EOF, whichever comes first if self._rbufsize <= 1: # Speed up unbuffered case assert data == "" buffers = [] recv = self._sock.recv while data != "\n": data = recv(1) if not data: break buffers.append(data) return "".join(buffers) nl = data.find('\n') if nl >= 0: nl += 1 self._rbuf = data[nl:] return data[:nl] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: data = self._sock.recv(self._rbufsize) if not data: break buffers.append(data) nl = data.find('\n') if nl >= 0: nl += 1 self._rbuf = data[nl:] buffers[-1] = data[:nl] break return "".join(buffers) else: # Read until size bytes or \n or EOF seen, whichever comes first nl = data.find('\n', 0, size) if nl >= 0: nl += 1 self._rbuf = data[nl:] return data[:nl] buf_len = len(data) if buf_len >= size: self._rbuf = data[size:] return data[:size] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: data = self._sock.recv(self._rbufsize) if not data: break buffers.append(data) left = size - buf_len nl = data.find('\n', 0, left) if nl >= 0: nl += 1 self._rbuf = data[nl:] buffers[-1] = data[:nl] break n = len(data) if n >= left: self._rbuf = data[left:] buffers[-1] = data[:left] break buf_len += n return "".join(buffers) def readlines(self, sizehint=0): total = 0 list = [] while True: line = self.readline() if not line: break list.append(line) total += len(line) if sizehint and total >= sizehint: break return list # Iterator protocols def __iter__(self): return self def next(self): line = self.readline() if not line: raise StopIteration return line
Python
# # Secret Labs' Regular Expression Engine # # convert template to internal format # # Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support module for sre""" import _sre, sys from sre_constants import * # XXX see PyPy hack in sre_constants to support both the 2.3 and 2.4 _sre.c implementation. #assert _sre.MAGIC == MAGIC, "SRE module mismatch" if _sre.CODESIZE == 2: MAXCODE = 65535 else: MAXCODE = 0xFFFFFFFFL def _identityfunction(x): return x def _compile(code, pattern, flags): # internal: compile a (sub)pattern emit = code.append _len = len LITERAL_CODES = {LITERAL:1, NOT_LITERAL:1} REPEATING_CODES = {REPEAT:1, MIN_REPEAT:1, MAX_REPEAT:1} SUCCESS_CODES = {SUCCESS:1, FAILURE:1} ASSERT_CODES = {ASSERT:1, ASSERT_NOT:1} for op, av in pattern: if op in LITERAL_CODES: if flags & SRE_FLAG_IGNORECASE: emit(OPCODES[OP_IGNORE[op]]) emit(_sre.getlower(av, flags)) else: emit(OPCODES[op]) emit(av) elif op is IN: if flags & SRE_FLAG_IGNORECASE: emit(OPCODES[OP_IGNORE[op]]) def fixup(literal, flags=flags): return _sre.getlower(literal, flags) else: emit(OPCODES[op]) fixup = _identityfunction skip = _len(code); emit(0) _compile_charset(av, flags, code, fixup) code[skip] = _len(code) - skip elif op is ANY: if flags & SRE_FLAG_DOTALL: emit(OPCODES[ANY_ALL]) else: emit(OPCODES[ANY]) elif op in REPEATING_CODES: if flags & SRE_FLAG_TEMPLATE: raise error, "internal: unsupported template operator" emit(OPCODES[REPEAT]) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip elif _simple(av) and op is not REPEAT: if op is MAX_REPEAT: emit(OPCODES[REPEAT_ONE]) else: emit(OPCODES[MIN_REPEAT_ONE]) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip else: emit(OPCODES[REPEAT]) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) code[skip] = _len(code) - skip if op is MAX_REPEAT: emit(OPCODES[MAX_UNTIL]) else: emit(OPCODES[MIN_UNTIL]) elif op is SUBPATTERN: if av[0]: emit(OPCODES[MARK]) emit((av[0]-1)*2) # _compile_info(code, av[1], flags) _compile(code, av[1], flags) if av[0]: emit(OPCODES[MARK]) emit((av[0]-1)*2+1) elif op in SUCCESS_CODES: emit(OPCODES[op]) elif op in ASSERT_CODES: emit(OPCODES[op]) skip = _len(code); emit(0) if av[0] >= 0: emit(0) # look ahead else: lo, hi = av[1].getwidth() if lo != hi: raise error, "look-behind requires fixed-width pattern" emit(lo) # look behind _compile(code, av[1], flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip elif op is CALL: emit(OPCODES[op]) skip = _len(code); emit(0) _compile(code, av, flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip elif op is AT: emit(OPCODES[op]) if flags & SRE_FLAG_MULTILINE: av = AT_MULTILINE.get(av, av) if flags & SRE_FLAG_LOCALE: av = AT_LOCALE.get(av, av) elif flags & SRE_FLAG_UNICODE: av = AT_UNICODE.get(av, av) emit(ATCODES[av]) elif op is BRANCH: emit(OPCODES[op]) tail = [] tailappend = tail.append for av in av[1]: skip = _len(code); emit(0) # _compile_info(code, av, flags) _compile(code, av, flags) emit(OPCODES[JUMP]) tailappend(_len(code)); emit(0) code[skip] = _len(code) - skip emit(0) # end of branch for tail in tail: code[tail] = _len(code) - tail elif op is CATEGORY: emit(OPCODES[op]) if flags & SRE_FLAG_LOCALE: av = CH_LOCALE[av] elif flags & SRE_FLAG_UNICODE: av = CH_UNICODE[av] emit(CHCODES[av]) elif op is GROUPREF: if flags & SRE_FLAG_IGNORECASE: emit(OPCODES[OP_IGNORE[op]]) else: emit(OPCODES[op]) emit(av-1) elif op is GROUPREF_EXISTS: emit(OPCODES[op]) emit((av[0]-1)*2) skipyes = _len(code); emit(0) _compile(code, av[1], flags) if av[2]: emit(OPCODES[JUMP]) skipno = _len(code); emit(0) code[skipyes] = _len(code) - skipyes + 1 _compile(code, av[2], flags) code[skipno] = _len(code) - skipno else: code[skipyes] = _len(code) - skipyes + 1 else: raise ValueError, ("unsupported operand type", op) def _compile_charset(charset, flags, code, fixup=None): # compile charset subprogram emit = code.append if fixup is None: fixup = _identityfunction for op, av in _optimize_charset(charset, fixup): emit(OPCODES[op]) if op is NEGATE: pass elif op is LITERAL: emit(fixup(av)) elif op is RANGE: emit(fixup(av[0])) emit(fixup(av[1])) elif op is CHARSET: code.extend(av) elif op is BIGCHARSET: code.extend(av) elif op is CATEGORY: if flags & SRE_FLAG_LOCALE: emit(CHCODES[CH_LOCALE[av]]) elif flags & SRE_FLAG_UNICODE: emit(CHCODES[CH_UNICODE[av]]) else: emit(CHCODES[av]) else: raise error, "internal: unsupported set operator" emit(OPCODES[FAILURE]) def _optimize_charset(charset, fixup): # internal: optimize character set out = [] outappend = out.append charmap = [0]*256 try: for op, av in charset: if op is NEGATE: outappend((op, av)) elif op is LITERAL: charmap[fixup(av)] = 1 elif op is RANGE: for i in range(fixup(av[0]), fixup(av[1])+1): charmap[i] = 1 elif op is CATEGORY: # XXX: could append to charmap tail return charset # cannot compress except IndexError: # character set contains unicode characters return _optimize_unicode(charset, fixup) # compress character map i = p = n = 0 runs = [] runsappend = runs.append for c in charmap: if c: if n == 0: p = i n = n + 1 elif n: runsappend((p, n)) n = 0 i = i + 1 if n: runsappend((p, n)) if len(runs) <= 2: # use literal/range for p, n in runs: if n == 1: outappend((LITERAL, p)) else: outappend((RANGE, (p, p+n-1))) if len(out) < len(charset): return out else: # use bitmap data = _mk_bitmap(charmap) outappend((CHARSET, data)) return out return charset def _mk_bitmap(bits): data = [] dataappend = data.append if _sre.CODESIZE == 2: start = (1, 0) else: start = (1L, 0L) m, v = start for c in bits: if c: v = v + m m = m + m if m > MAXCODE: dataappend(v) m, v = start return data # To represent a big charset, first a bitmap of all characters in the # set is constructed. Then, this bitmap is sliced into chunks of 256 # characters, duplicate chunks are eliminitated, and each chunk is # given a number. In the compiled expression, the charset is # represented by a 16-bit word sequence, consisting of one word for # the number of different chunks, a sequence of 256 bytes (128 words) # of chunk numbers indexed by their original chunk position, and a # sequence of chunks (16 words each). # Compression is normally good: in a typical charset, large ranges of # Unicode will be either completely excluded (e.g. if only cyrillic # letters are to be matched), or completely included (e.g. if large # subranges of Kanji match). These ranges will be represented by # chunks of all one-bits or all zero-bits. # Matching can be also done efficiently: the more significant byte of # the Unicode character is an index into the chunk number, and the # less significant byte is a bit index in the chunk (just like the # CHARSET matching). # In UCS-4 mode, the BIGCHARSET opcode still supports only subsets # of the basic multilingual plane; an efficient representation # for all of UTF-16 has not yet been developed. This means, # in particular, that negated charsets cannot be represented as # bigcharsets. def _optimize_unicode(charset, fixup): try: import array except ImportError: return charset charmap = [0]*65536 negate = 0 try: for op, av in charset: if op is NEGATE: negate = 1 elif op is LITERAL: charmap[fixup(av)] = 1 elif op is RANGE: for i in xrange(fixup(av[0]), fixup(av[1])+1): charmap[i] = 1 elif op is CATEGORY: # XXX: could expand category return charset # cannot compress except IndexError: # non-BMP characters return charset if negate: if sys.maxunicode != 65535: # XXX: negation does not work with big charsets return charset for i in xrange(65536): charmap[i] = not charmap[i] comps = {} mapping = [0]*256 block = 0 data = [] for i in xrange(256): chunk = tuple(charmap[i*256:(i+1)*256]) new = comps.setdefault(chunk, block) mapping[i] = new if new == block: block = block + 1 data = data + _mk_bitmap(chunk) header = [block] if _sre.CODESIZE == 2: code = 'H' else: code = 'I' # Convert block indices to byte array of 256 bytes mapping = array.array('b', mapping).tostring() # Convert byte array to word array mapping = array.array(code, mapping) assert mapping.itemsize == _sre.CODESIZE header = header + mapping.tolist() data[0:0] = header return [(BIGCHARSET, data)] def _simple(av): # check if av is a "simple" operator lo, hi = av[2].getwidth() if lo == 0 and hi == MAXREPEAT: raise error, "nothing to repeat" return lo == hi == 1 and av[2][0][0] != SUBPATTERN def _compile_info(code, pattern, flags): # internal: compile an info block. in the current version, # this contains min/max pattern width, and an optional literal # prefix or a character map lo, hi = pattern.getwidth() if lo == 0: return # not worth it # look for a literal prefix prefix = [] prefixappend = prefix.append prefix_skip = 0 charset = [] # not used charsetappend = charset.append if not (flags & SRE_FLAG_IGNORECASE): # look for literal prefix for op, av in pattern.data: if op is LITERAL: if len(prefix) == prefix_skip: prefix_skip = prefix_skip + 1 prefixappend(av) elif op is SUBPATTERN and len(av[1]) == 1: op, av = av[1][0] if op is LITERAL: prefixappend(av) else: break else: break # if no prefix, look for charset prefix if not prefix and pattern.data: op, av = pattern.data[0] if op is SUBPATTERN and av[1]: op, av = av[1][0] if op is LITERAL: charsetappend((op, av)) elif op is BRANCH: c = [] cappend = c.append for p in av[1]: if not p: break op, av = p[0] if op is LITERAL: cappend((op, av)) else: break else: charset = c elif op is BRANCH: c = [] cappend = c.append for p in av[1]: if not p: break op, av = p[0] if op is LITERAL: cappend((op, av)) else: break else: charset = c elif op is IN: charset = av ## if prefix: ## print "*** PREFIX", prefix, prefix_skip ## if charset: ## print "*** CHARSET", charset # add an info block emit = code.append emit(OPCODES[INFO]) skip = len(code); emit(0) # literal flag mask = 0 if prefix: mask = SRE_INFO_PREFIX if len(prefix) == prefix_skip == len(pattern.data): mask = mask + SRE_INFO_LITERAL elif charset: mask = mask + SRE_INFO_CHARSET emit(mask) # pattern length if lo < MAXCODE: emit(lo) else: emit(MAXCODE) prefix = prefix[:MAXCODE] if hi < MAXCODE: emit(hi) else: emit(0) # add literal prefix if prefix: emit(len(prefix)) # length emit(prefix_skip) # skip code.extend(prefix) # generate overlap table table = [-1] + ([0]*len(prefix)) for i in xrange(len(prefix)): table[i+1] = table[i]+1 while table[i+1] > 0 and prefix[i] != prefix[table[i+1]-1]: table[i+1] = table[table[i+1]-1]+1 code.extend(table[1:]) # don't store first entry elif charset: _compile_charset(charset, flags, code) code[skip] = len(code) - skip try: unicode except NameError: STRING_TYPES = (type(""),) else: STRING_TYPES = (type(""), type(unicode(""))) def isstring(obj): for tp in STRING_TYPES: if isinstance(obj, tp): return 1 return 0 def _code(p, flags): flags = p.pattern.flags | flags code = [] # compile info block _compile_info(code, p, flags) # compile the pattern _compile(code, p.data, flags) code.append(OPCODES[SUCCESS]) return code def compile(p, flags=0): # internal: convert pattern list to internal format if isstring(p): import sre_parse pattern = p p = sre_parse.parse(p, flags) else: pattern = None code = _code(p, flags) # print code # XXX: <fl> get rid of this limitation! if p.pattern.groups > 100: raise AssertionError( "sorry, but this version only supports 100 named groups" ) # map in either direction groupindex = p.pattern.groupdict indexgroup = [None] * p.pattern.groups for k, i in groupindex.items(): indexgroup[i] = k return _sre.compile( pattern, flags, code, p.pattern.groups-1, groupindex, indexgroup )
Python
# Notes about changes in this file: # a prefix of "dont_" means the test makes no sense, # because we don't use cPickle at all. # "xxx_" means it works and can be done, but takes ages. # When PyPy gets really fast, we should remove "xxx_". import unittest import pickle import cPickle import pickletools import copy_reg from test.test_support import TestFailed, have_unicode, TESTFN # Tests that try a number of pickle protocols should have a # for proto in protocols: # kind of outer loop. assert pickle.HIGHEST_PROTOCOL == cPickle.HIGHEST_PROTOCOL == 2 protocols = range(pickle.HIGHEST_PROTOCOL + 1) # Return True if opcode code appears in the pickle, else False. def opcode_in_pickle(code, pickle): for op, dummy, dummy in pickletools.genops(pickle): if op.code == code: return True return False # Return the number of times opcode code appears in pickle. def count_opcode(code, pickle): n = 0 for op, dummy, dummy in pickletools.genops(pickle): if op.code == code: n += 1 return n # We can't very well test the extension registry without putting known stuff # in it, but we have to be careful to restore its original state. Code # should do this: # # e = ExtensionSaver(extension_code) # try: # fiddle w/ the extension registry's stuff for extension_code # finally: # e.restore() class ExtensionSaver: # Remember current registration for code (if any), and remove it (if # there is one). def __init__(self, code): self.code = code if code in copy_reg._inverted_registry: self.pair = copy_reg._inverted_registry[code] copy_reg.remove_extension(self.pair[0], self.pair[1], code) else: self.pair = None # Restore previous registration for code. def restore(self): code = self.code curpair = copy_reg._inverted_registry.get(code) if curpair is not None: copy_reg.remove_extension(curpair[0], curpair[1], code) pair = self.pair if pair is not None: copy_reg.add_extension(pair[0], pair[1], code) class C: def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) import __main__ __main__.C = C C.__module__ = "__main__" class myint(int): def __init__(self, x): self.str = str(x) class initarg(C): def __init__(self, a, b): self.a = a self.b = b def __getinitargs__(self): return self.a, self.b class metaclass(type): pass class use_metaclass(object): __metaclass__ = metaclass # DATA0 .. DATA2 are the pickles we expect under the various protocols, for # the object returned by create_data(). # break into multiple strings to avoid confusing font-lock-mode DATA0 = """(lp1 I0 aL1L aF2 ac__builtin__ complex p2 """ + \ """(F3 F0 tRp3 aI1 aI-1 aI255 aI-255 aI-256 aI65535 aI-65535 aI-65536 aI2147483647 aI-2147483647 aI-2147483648 a""" + \ """(S'abc' p4 g4 """ + \ """(i__main__ C p5 """ + \ """(dp6 S'foo' p7 I1 sS'bar' p8 I2 sbg5 tp9 ag9 aI5 a. """ # Disassembly of DATA0. DATA0_DIS = """\ 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 1 5: I INT 0 8: a APPEND 9: L LONG 1L 13: a APPEND 14: F FLOAT 2.0 17: a APPEND 18: c GLOBAL '__builtin__ complex' 39: p PUT 2 42: ( MARK 43: F FLOAT 3.0 46: F FLOAT 0.0 49: t TUPLE (MARK at 42) 50: R REDUCE 51: p PUT 3 54: a APPEND 55: I INT 1 58: a APPEND 59: I INT -1 63: a APPEND 64: I INT 255 69: a APPEND 70: I INT -255 76: a APPEND 77: I INT -256 83: a APPEND 84: I INT 65535 91: a APPEND 92: I INT -65535 100: a APPEND 101: I INT -65536 109: a APPEND 110: I INT 2147483647 122: a APPEND 123: I INT -2147483647 136: a APPEND 137: I INT -2147483648 150: a APPEND 151: ( MARK 152: S STRING 'abc' 159: p PUT 4 162: g GET 4 165: ( MARK 166: i INST '__main__ C' (MARK at 165) 178: p PUT 5 181: ( MARK 182: d DICT (MARK at 181) 183: p PUT 6 186: S STRING 'foo' 193: p PUT 7 196: I INT 1 199: s SETITEM 200: S STRING 'bar' 207: p PUT 8 210: I INT 2 213: s SETITEM 214: b BUILD 215: g GET 5 218: t TUPLE (MARK at 151) 219: p PUT 9 222: a APPEND 223: g GET 9 226: a APPEND 227: I INT 5 230: a APPEND 231: . STOP highest protocol among opcodes = 0 """ DATA1 = (']q\x01(K\x00L1L\nG@\x00\x00\x00\x00\x00\x00\x00' 'c__builtin__\ncomplex\nq\x02(G@\x08\x00\x00\x00\x00\x00' '\x00G\x00\x00\x00\x00\x00\x00\x00\x00tRq\x03K\x01J\xff\xff' '\xff\xffK\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xff' 'J\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00' '\x00\x80J\x00\x00\x00\x80(U\x03abcq\x04h\x04(c__main__\n' 'C\nq\x05oq\x06}q\x07(U\x03fooq\x08K\x01U\x03barq\tK\x02ubh' '\x06tq\nh\nK\x05e.' ) # Disassembly of DATA1. DATA1_DIS = """\ 0: ] EMPTY_LIST 1: q BINPUT 1 3: ( MARK 4: K BININT1 0 6: L LONG 1L 10: G BINFLOAT 2.0 19: c GLOBAL '__builtin__ complex' 40: q BINPUT 2 42: ( MARK 43: G BINFLOAT 3.0 52: G BINFLOAT 0.0 61: t TUPLE (MARK at 42) 62: R REDUCE 63: q BINPUT 3 65: K BININT1 1 67: J BININT -1 72: K BININT1 255 74: J BININT -255 79: J BININT -256 84: M BININT2 65535 87: J BININT -65535 92: J BININT -65536 97: J BININT 2147483647 102: J BININT -2147483647 107: J BININT -2147483648 112: ( MARK 113: U SHORT_BINSTRING 'abc' 118: q BINPUT 4 120: h BINGET 4 122: ( MARK 123: c GLOBAL '__main__ C' 135: q BINPUT 5 137: o OBJ (MARK at 122) 138: q BINPUT 6 140: } EMPTY_DICT 141: q BINPUT 7 143: ( MARK 144: U SHORT_BINSTRING 'foo' 149: q BINPUT 8 151: K BININT1 1 153: U SHORT_BINSTRING 'bar' 158: q BINPUT 9 160: K BININT1 2 162: u SETITEMS (MARK at 143) 163: b BUILD 164: h BINGET 6 166: t TUPLE (MARK at 112) 167: q BINPUT 10 169: h BINGET 10 171: K BININT1 5 173: e APPENDS (MARK at 3) 174: . STOP highest protocol among opcodes = 1 """ DATA2 = ('\x80\x02]q\x01(K\x00\x8a\x01\x01G@\x00\x00\x00\x00\x00\x00\x00' 'c__builtin__\ncomplex\nq\x02G@\x08\x00\x00\x00\x00\x00\x00G\x00' '\x00\x00\x00\x00\x00\x00\x00\x86Rq\x03K\x01J\xff\xff\xff\xffK' '\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xff' 'J\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00' '\x80(U\x03abcq\x04h\x04(c__main__\nC\nq\x05oq\x06}q\x07(U\x03foo' 'q\x08K\x01U\x03barq\tK\x02ubh\x06tq\nh\nK\x05e.') # Disassembly of DATA2. DATA2_DIS = """\ 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 1 5: ( MARK 6: K BININT1 0 8: \x8a LONG1 1L 11: G BINFLOAT 2.0 20: c GLOBAL '__builtin__ complex' 41: q BINPUT 2 43: G BINFLOAT 3.0 52: G BINFLOAT 0.0 61: \x86 TUPLE2 62: R REDUCE 63: q BINPUT 3 65: K BININT1 1 67: J BININT -1 72: K BININT1 255 74: J BININT -255 79: J BININT -256 84: M BININT2 65535 87: J BININT -65535 92: J BININT -65536 97: J BININT 2147483647 102: J BININT -2147483647 107: J BININT -2147483648 112: ( MARK 113: U SHORT_BINSTRING 'abc' 118: q BINPUT 4 120: h BINGET 4 122: ( MARK 123: c GLOBAL '__main__ C' 135: q BINPUT 5 137: o OBJ (MARK at 122) 138: q BINPUT 6 140: } EMPTY_DICT 141: q BINPUT 7 143: ( MARK 144: U SHORT_BINSTRING 'foo' 149: q BINPUT 8 151: K BININT1 1 153: U SHORT_BINSTRING 'bar' 158: q BINPUT 9 160: K BININT1 2 162: u SETITEMS (MARK at 143) 163: b BUILD 164: h BINGET 6 166: t TUPLE (MARK at 112) 167: q BINPUT 10 169: h BINGET 10 171: K BININT1 5 173: e APPENDS (MARK at 5) 174: . STOP highest protocol among opcodes = 2 """ def create_data(): c = C() c.foo = 1 c.bar = 2 x = [0, 1L, 2.0, 3.0+0j] # Append some integer test cases at cPickle.c's internal size # cutoffs. uint1max = 0xff uint2max = 0xffff int4max = 0x7fffffff x.extend([1, -1, uint1max, -uint1max, -uint1max-1, uint2max, -uint2max, -uint2max-1, int4max, -int4max, -int4max-1]) y = ('abc', 'abc', c, c) x.append(y) x.append(y) x.append(5) return x class AbstractPickleTests(unittest.TestCase): # Subclass must define self.dumps, self.loads, self.error. _testdata = create_data() def setUp(self): pass def test_misc(self): # test various datatypes not tested by testdata for proto in protocols: x = myint(4) s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) x = (1, ()) s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) x = initarg(1, x) s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) # XXX test __reduce__ protocol? def test_roundtrip_equality(self): expected = self._testdata for proto in protocols: s = self.dumps(expected, proto) got = self.loads(s) self.assertEqual(expected, got) def test_load_from_canned_string(self): expected = self._testdata for canned in DATA0, DATA1, DATA2: got = self.loads(canned) self.assertEqual(expected, got) # There are gratuitous differences between pickles produced by # pickle and cPickle, largely because cPickle starts PUT indices at # 1 and pickle starts them at 0. See XXX comment in cPickle's put2() -- # there's a comment with an exclamation point there whose meaning # is a mystery. cPickle also suppresses PUT for objects with a refcount # of 1. def dont_test_disassembly(self): from cStringIO import StringIO from pickletools import dis for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS): s = self.dumps(self._testdata, proto) filelike = StringIO() dis(s, out=filelike) got = filelike.getvalue() self.assertEqual(expected, got) def test_recursive_list(self): l = [] l.append(l) for proto in protocols: s = self.dumps(l, proto) x = self.loads(s) self.assertEqual(len(x), 1) self.assert_(x is x[0]) def test_recursive_dict(self): d = {} d[1] = d for proto in protocols: s = self.dumps(d, proto) x = self.loads(s) self.assertEqual(x.keys(), [1]) self.assert_(x[1] is x) def test_recursive_inst(self): i = C() i.attr = i for proto in protocols: s = self.dumps(i, 2) x = self.loads(s) self.assertEqual(dir(x), dir(i)) self.assert_(x.attr is x) def test_recursive_multi(self): l = [] d = {1:l} i = C() i.attr = d l.append(i) for proto in protocols: s = self.dumps(l, proto) x = self.loads(s) self.assertEqual(len(x), 1) self.assertEqual(dir(x[0]), dir(i)) self.assertEqual(x[0].attr.keys(), [1]) self.assert_(x[0].attr[1] is x) def test_garyp(self): self.assertRaises(self.error, self.loads, 'garyp') def test_insecure_strings(self): insecure = ["abc", "2 + 2", # not quoted #"'abc' + 'def'", # not a single quoted string "'abc", # quote is not closed "'abc\"", # open quote and close quote don't match "'abc' ?", # junk after close quote "'\\'", # trailing backslash # some tests of the quoting rules #"'abc\"\''", #"'\\\\a\'\'\'\\\'\\\\\''", ] for s in insecure: buf = "S" + s + "\012p0\012." self.assertRaises(ValueError, self.loads, buf) if have_unicode: def test_unicode(self): endcases = [unicode(''), unicode('<\\u>'), unicode('<\\\u1234>'), unicode('<\n>'), unicode('<\\>')] for proto in protocols: for u in endcases: p = self.dumps(u, proto) u2 = self.loads(p) self.assertEqual(u2, u) def test_ints(self): import sys for proto in protocols: n = sys.maxint while n: for expected in (-n, n): s = self.dumps(expected, proto) n2 = self.loads(s) self.assertEqual(expected, n2) n = n >> 1 def test_maxint64(self): maxint64 = (1L << 63) - 1 data = 'I' + str(maxint64) + '\n.' got = self.loads(data) self.assertEqual(got, maxint64) # Try too with a bogus literal. data = 'I' + str(maxint64) + 'JUNK\n.' self.assertRaises(ValueError, self.loads, data) def xxx_test_long(self): for proto in protocols: # 256 bytes is where LONG4 begins. for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257: nbase = 1L << nbits for npos in nbase-1, nbase, nbase+1: for n in npos, -npos: pickle = self.dumps(n, proto) got = self.loads(pickle) self.assertEqual(n, got) # Try a monster. This is quadratic-time in protos 0 & 1, so don't # bother with those. nbase = long("deadbeeffeedface", 16) nbase += nbase << 1000000 for n in nbase, -nbase: p = self.dumps(n, 2) got = self.loads(p) self.assertEqual(n, got) def test_reduce(self): pass def test_getinitargs(self): pass def test_metaclass(self): a = use_metaclass() for proto in protocols: s = self.dumps(a, proto) b = self.loads(s) self.assertEqual(a.__class__, b.__class__) def test_structseq(self): import time import os t = time.localtime() for proto in protocols: s = self.dumps(t, proto) u = self.loads(s) self.assertEqual(t, u) if hasattr(os, "stat"): t = os.stat(os.curdir) s = self.dumps(t, proto) u = self.loads(s) self.assertEqual(t, u) if hasattr(os, "statvfs"): t = os.statvfs(os.curdir) s = self.dumps(t, proto) u = self.loads(s) self.assertEqual(t, u) # Tests for protocol 2 def test_proto(self): build_none = pickle.NONE + pickle.STOP for proto in protocols: expected = build_none if proto >= 2: expected = pickle.PROTO + chr(proto) + expected p = self.dumps(None, proto) self.assertEqual(p, expected) oob = protocols[-1] + 1 # a future protocol badpickle = pickle.PROTO + chr(oob) + build_none try: self.loads(badpickle) except ValueError, detail: self.failUnless(str(detail).startswith( "unsupported pickle protocol")) else: self.fail("expected bad protocol number to raise ValueError") def test_long1(self): x = 12345678910111213141516178920L for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2) def test_long4(self): x = 12345678910111213141516178920L << (256*8) for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) self.assertEqual(opcode_in_pickle(pickle.LONG4, s), proto >= 2) def test_short_tuples(self): # Map (proto, len(tuple)) to expected opcode. expected_opcode = {(0, 0): pickle.TUPLE, (0, 1): pickle.TUPLE, (0, 2): pickle.TUPLE, (0, 3): pickle.TUPLE, (0, 4): pickle.TUPLE, (1, 0): pickle.EMPTY_TUPLE, (1, 1): pickle.TUPLE, (1, 2): pickle.TUPLE, (1, 3): pickle.TUPLE, (1, 4): pickle.TUPLE, (2, 0): pickle.EMPTY_TUPLE, (2, 1): pickle.TUPLE1, (2, 2): pickle.TUPLE2, (2, 3): pickle.TUPLE3, (2, 4): pickle.TUPLE, } a = () b = (1,) c = (1, 2) d = (1, 2, 3) e = (1, 2, 3, 4) for proto in protocols: for x in a, b, c, d, e: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y, (proto, x, s, y)) expected = expected_opcode[proto, len(x)] self.assertEqual(opcode_in_pickle(expected, s), True) def test_singletons(self): # Map (proto, singleton) to expected opcode. expected_opcode = {(0, None): pickle.NONE, (1, None): pickle.NONE, (2, None): pickle.NONE, (0, True): pickle.INT, (1, True): pickle.INT, (2, True): pickle.NEWTRUE, (0, False): pickle.INT, (1, False): pickle.INT, (2, False): pickle.NEWFALSE, } for proto in protocols: for x in None, False, True: s = self.dumps(x, proto) y = self.loads(s) self.assert_(x is y, (proto, x, s, y)) expected = expected_opcode[proto, x] self.assertEqual(opcode_in_pickle(expected, s), True) def test_newobj_tuple(self): x = MyTuple([1, 2, 3]) x.foo = 42 x.bar = "hello" for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(tuple(x), tuple(y)) self.assertEqual(x.__dict__, y.__dict__) def test_newobj_list(self): x = MyList([1, 2, 3]) x.foo = 42 x.bar = "hello" for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) def test_newobj_generic(self): for proto in protocols: for C in myclasses: B = C.__base__ x = C(C.sample) x.foo = 42 s = self.dumps(x, proto) y = self.loads(s) detail = (proto, C, B, x, y, type(y)) self.assertEqual(B(x), B(y), detail) self.assertEqual(x.__dict__, y.__dict__, detail) # Register a type with copy_reg, with extension code extcode. Pickle # an object of that type. Check that the resulting pickle uses opcode # (EXT[124]) under proto 2, and not in proto 1. def produce_global_ext(self, extcode, opcode): e = ExtensionSaver(extcode) try: copy_reg.add_extension(__name__, "MyList", extcode) x = MyList([1, 2, 3]) x.foo = 42 x.bar = "hello" # Dump using protocol 1 for comparison. s1 = self.dumps(x, 1) self.assert_(__name__ in s1) self.assert_("MyList" in s1) self.assertEqual(opcode_in_pickle(opcode, s1), False) y = self.loads(s1) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) # Dump using protocol 2 for test. s2 = self.dumps(x, 2) self.assert_(__name__ not in s2) self.assert_("MyList" not in s2) self.assertEqual(opcode_in_pickle(opcode, s2), True) y = self.loads(s2) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) finally: e.restore() def test_global_ext1(self): self.produce_global_ext(0x00000001, pickle.EXT1) # smallest EXT1 code self.produce_global_ext(0x000000ff, pickle.EXT1) # largest EXT1 code def test_global_ext2(self): self.produce_global_ext(0x00000100, pickle.EXT2) # smallest EXT2 code self.produce_global_ext(0x0000ffff, pickle.EXT2) # largest EXT2 code self.produce_global_ext(0x0000abcd, pickle.EXT2) # check endianness def test_global_ext4(self): self.produce_global_ext(0x00010000, pickle.EXT4) # smallest EXT4 code self.produce_global_ext(0x7fffffff, pickle.EXT4) # largest EXT4 code self.produce_global_ext(0x12abcdef, pickle.EXT4) # check endianness def xxx_test_list_chunking(self): n = 10 # too small to chunk x = range(n) for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) num_appends = count_opcode(pickle.APPENDS, s) self.assertEqual(num_appends, proto > 0) n = 2500 # expect at least two chunks when proto > 0 x = range(n) for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) num_appends = count_opcode(pickle.APPENDS, s) if proto == 0: self.assertEqual(num_appends, 0) else: self.failUnless(num_appends >= 2) def xxx_test_dict_chunking(self): n = 10 # too small to chunk x = dict.fromkeys(range(n)) for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) num_setitems = count_opcode(pickle.SETITEMS, s) self.assertEqual(num_setitems, proto > 0) n = 2500 # expect at least two chunks when proto > 0 x = dict.fromkeys(range(n)) for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y) num_setitems = count_opcode(pickle.SETITEMS, s) if proto == 0: self.assertEqual(num_setitems, 0) else: self.failUnless(num_setitems >= 2) def test_simple_newobj(self): x = object.__new__(SimpleNewObj) # avoid __init__ x.abc = 666 for proto in protocols: s = self.dumps(x, proto) self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2) y = self.loads(s) # will raise TypeError if __init__ called self.assertEqual(y.abc, 666) self.assertEqual(x.__dict__, y.__dict__) def test_newobj_list_slots(self): x = SlotList([1, 2, 3]) x.foo = 42 x.bar = "hello" s = self.dumps(x, 2) y = self.loads(s) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) self.assertEqual(x.foo, y.foo) self.assertEqual(x.bar, y.bar) def test_reduce_overrides_default_reduce_ex(self): for proto in 0, 1, 2: x = REX_one() self.assertEqual(x._reduce_called, 0) s = self.dumps(x, proto) self.assertEqual(x._reduce_called, 1) y = self.loads(s) self.assertEqual(y._reduce_called, 0) def test_reduce_ex_called(self): for proto in 0, 1, 2: x = REX_two() self.assertEqual(x._proto, None) s = self.dumps(x, proto) self.assertEqual(x._proto, proto) y = self.loads(s) self.assertEqual(y._proto, None) def test_reduce_ex_overrides_reduce(self): for proto in 0, 1, 2: x = REX_three() self.assertEqual(x._proto, None) s = self.dumps(x, proto) self.assertEqual(x._proto, proto) y = self.loads(s) self.assertEqual(y._proto, None) # Test classes for reduce_ex class REX_one(object): _reduce_called = 0 def __reduce__(self): self._reduce_called = 1 return REX_one, () # No __reduce_ex__ here, but inheriting it from object class REX_two(object): _proto = None def __reduce_ex__(self, proto): self._proto = proto return REX_two, () # No __reduce__ here, but inheriting it from object class REX_three(object): _proto = None def __reduce_ex__(self, proto): self._proto = proto return REX_two, () def __reduce__(self): raise TestFailed, "This __reduce__ shouldn't be called" # Test classes for newobj class MyInt(int): sample = 1 class MyLong(long): sample = 1L class MyFloat(float): sample = 1.0 class MyComplex(complex): sample = 1.0 + 0.0j class MyStr(str): sample = "hello" class MyUnicode(unicode): sample = u"hello \u1234" class MyTuple(tuple): sample = (1, 2, 3) class MyList(list): sample = [1, 2, 3] class MyDict(dict): sample = {"a": 1, "b": 2} myclasses = [MyInt, MyLong, MyFloat, MyComplex, MyStr, MyUnicode, MyTuple, MyList, MyDict] class SlotList(MyList): __slots__ = ["foo"] class SimpleNewObj(object): def __init__(self, a, b, c): # raise an error, to make sure this isn't called raise TypeError("SimpleNewObj.__init__() didn't expect to get called") class AbstractPickleModuleTests(unittest.TestCase): def test_dump_closed_file(self): import os f = open(TESTFN, "w") try: f.close() self.assertRaises(ValueError, self.module.dump, 123, f) finally: os.remove(TESTFN) def test_load_closed_file(self): import os f = open(TESTFN, "w") try: f.close() self.assertRaises(ValueError, self.module.dump, 123, f) finally: os.remove(TESTFN) def test_highest_protocol(self): # Of course this needs to be changed when HIGHEST_PROTOCOL changes. self.assertEqual(self.module.HIGHEST_PROTOCOL, 2) def test_callapi(self): from cStringIO import StringIO f = StringIO() # With and without keyword arguments self.module.dump(123, f, -1) self.module.dump(123, file=f, protocol=-1) self.module.dumps(123, -1) self.module.dumps(123, protocol=-1) self.module.Pickler(f, -1) self.module.Pickler(f, protocol=-1) class AbstractPersistentPicklerTests(unittest.TestCase): # This class defines persistent_id() and persistent_load() # functions that should be used by the pickler. All even integers # are pickled using persistent ids. def persistent_id(self, object): if isinstance(object, int) and object % 2 == 0: self.id_count += 1 return str(object) else: return None def persistent_load(self, oid): self.load_count += 1 object = int(oid) assert object % 2 == 0 return object def test_persistence(self): self.id_count = 0 self.load_count = 0 L = range(10) self.assertEqual(self.loads(self.dumps(L)), L) self.assertEqual(self.id_count, 5) self.assertEqual(self.load_count, 5) def test_bin_persistence(self): self.id_count = 0 self.load_count = 0 L = range(10) self.assertEqual(self.loads(self.dumps(L, 1)), L) self.assertEqual(self.id_count, 5) self.assertEqual(self.load_count, 5)
Python
#!/usr/bin/env python import unittest import random import time import pickle import warnings from math import log, exp, sqrt, pi from test import test_support class TestBasicOps(unittest.TestCase): # Superclass with tests common to all generators. # Subclasses must arrange for self.gen to retrieve the Random instance # to be tested. def randomlist(self, n): """Helper function to make a list of random numbers""" return [self.gen.random() for i in xrange(n)] def test_autoseed(self): self.gen.seed() state1 = self.gen.getstate() time.sleep(0.1) self.gen.seed() # diffent seeds at different times state2 = self.gen.getstate() self.assertNotEqual(state1, state2) def test_saverestore(self): N = 1000 self.gen.seed() state = self.gen.getstate() randseq = self.randomlist(N) self.gen.setstate(state) # should regenerate the same sequence self.assertEqual(randseq, self.randomlist(N)) def test_seedargs(self): for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20), 3.14, 1+2j, 'a', tuple('abc')]: self.gen.seed(arg) for arg in [range(3), dict(one=1)]: self.assertRaises(TypeError, self.gen.seed, arg) self.assertRaises(TypeError, self.gen.seed, 1, 2) self.assertRaises(TypeError, type(self.gen), []) def test_jumpahead(self): self.gen.seed() state1 = self.gen.getstate() self.gen.jumpahead(100) state2 = self.gen.getstate() # s/b distinct from state1 self.assertNotEqual(state1, state2) self.gen.jumpahead(100) state3 = self.gen.getstate() # s/b distinct from state2 self.assertNotEqual(state2, state3) self.assertRaises(TypeError, self.gen.jumpahead) # needs an arg # wrong type - can get ValueError if by any chance "ick" compares < 0 self.assertRaises((TypeError, ValueError), self.gen.jumpahead, "ick") self.assertRaises(TypeError, self.gen.jumpahead, 2.3) # wrong type self.assertRaises(TypeError, self.gen.jumpahead, 2, 3) # too many def test_sample(self): # For the entire allowable range of 0 <= k <= N, validate that # the sample is of the correct length and contains only unique items N = 100 population = xrange(N) for k in xrange(N+1): s = self.gen.sample(population, k) self.assertEqual(len(s), k) uniq = set(s) self.assertEqual(len(uniq), k) self.failUnless(uniq <= set(population)) self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0 def test_sample_distribution(self): # For the entire allowable range of 0 <= k <= N, validate that # sample generates all possible permutations n = 5 pop = range(n) trials = 10000 # large num prevents false negatives without slowing normal case def factorial(n): return reduce(int.__mul__, xrange(1, n), 1) for k in xrange(n): expected = factorial(n) // factorial(n-k) perms = {} for i in xrange(trials): perms[tuple(self.gen.sample(pop, k))] = None if len(perms) == expected: break else: self.fail() def test_sample_inputs(self): # SF bug #801342 -- population can be any iterable defining __len__() self.gen.sample(set(range(20)), 2) self.gen.sample(range(20), 2) self.gen.sample(xrange(20), 2) self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2) self.gen.sample(str('abcdefghijklmnopqrst'), 2) self.gen.sample(tuple('abcdefghijklmnopqrst'), 2) def test_gauss(self): # Ensure that the seed() method initializes all the hidden state. In # particular, through 2.2.1 it failed to reset a piece of state used # by (and only by) the .gauss() method. for seed in 1, 12, 123, 1234, 12345, 123456, 654321: self.gen.seed(seed) x1 = self.gen.random() y1 = self.gen.gauss(0, 1) self.gen.seed(seed) x2 = self.gen.random() y2 = self.gen.gauss(0, 1) self.assertEqual(x1, x2) self.assertEqual(y1, y2) def test_pickling(self): state = pickle.dumps(self.gen) origseq = [self.gen.random() for i in xrange(10)] newgen = pickle.loads(state) restoredseq = [newgen.random() for i in xrange(10)] self.assertEqual(origseq, restoredseq) class WichmannHill_TestBasicOps(TestBasicOps): gen = random.WichmannHill() def test_setstate_first_arg(self): self.assertRaises(ValueError, self.gen.setstate, (2, None, None)) def test_strong_jumpahead(self): # tests that jumpahead(n) semantics correspond to n calls to random() N = 1000 s = self.gen.getstate() self.gen.jumpahead(N) r1 = self.gen.random() # now do it the slow way self.gen.setstate(s) for i in xrange(N): self.gen.random() r2 = self.gen.random() self.assertEqual(r1, r2) def test_gauss_with_whseed(self): # Ensure that the seed() method initializes all the hidden state. In # particular, through 2.2.1 it failed to reset a piece of state used # by (and only by) the .gauss() method. for seed in 1, 12, 123, 1234, 12345, 123456, 654321: self.gen.whseed(seed) x1 = self.gen.random() y1 = self.gen.gauss(0, 1) self.gen.whseed(seed) x2 = self.gen.random() y2 = self.gen.gauss(0, 1) self.assertEqual(x1, x2) self.assertEqual(y1, y2) def test_bigrand(self): # Verify warnings are raised when randrange is too large for random() oldfilters = warnings.filters[:] warnings.filterwarnings("error", "Underlying random") self.assertRaises(UserWarning, self.gen.randrange, 2**60) warnings.filters[:] = oldfilters class SystemRandom_TestBasicOps(TestBasicOps): gen = random.SystemRandom() def test_autoseed(self): # Doesn't need to do anything except not fail self.gen.seed() def test_saverestore(self): self.assertRaises(NotImplementedError, self.gen.getstate) self.assertRaises(NotImplementedError, self.gen.setstate, None) def test_seedargs(self): # Doesn't need to do anything except not fail self.gen.seed(100) def test_jumpahead(self): # Doesn't need to do anything except not fail self.gen.jumpahead(100) def test_gauss(self): self.gen.gauss_next = None self.gen.seed(100) self.assertEqual(self.gen.gauss_next, None) def test_pickling(self): self.assertRaises(NotImplementedError, pickle.dumps, self.gen) def test_53_bits_per_float(self): # This should pass whenever a C double has 53 bit precision. span = 2 ** 53 cum = 0 for i in xrange(100): cum |= int(self.gen.random() * span) self.assertEqual(cum, span-1) def test_bigrand(self): # The randrange routine should build-up the required number of bits # in stages so that all bit positions are active. span = 2 ** 500 cum = 0 for i in xrange(100): r = self.gen.randrange(span) self.assert_(0 <= r < span) cum |= r self.assertEqual(cum, span-1) def test_bigrand_ranges(self): for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: start = self.gen.randrange(2 ** i) stop = self.gen.randrange(2 ** (i-2)) if stop <= start: return self.assert_(start <= self.gen.randrange(start, stop) < stop) def test_rangelimits(self): for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: self.assertEqual(set(range(start,stop)), set([self.gen.randrange(start,stop) for i in xrange(100)])) def test_genrandbits(self): # Verify ranges for k in xrange(1, 1000): self.assert_(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: cum = 0 for i in xrange(100): cum |= getbits(span) self.assertEqual(cum, 2**span-1) # Verify argument checking self.assertRaises(TypeError, self.gen.getrandbits) self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) self.assertRaises(ValueError, self.gen.getrandbits, 0) self.assertRaises(ValueError, self.gen.getrandbits, -1) self.assertRaises(TypeError, self.gen.getrandbits, 10.1) def test_randbelow_logic(self, _log=log, int=int): # check bitcount transition points: 2**i and 2**(i+1)-1 # show that: k = int(1.001 + _log(n, 2)) # is equal to or one greater than the number of bits in n for i in xrange(1, 1000): n = 1L << i # check an exact power of two numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) self.assert_(n == 2**(k-1)) n += n - 1 # check 1 below the next power of two k = int(1.00001 + _log(n, 2)) self.assert_(k in [numbits, numbits+1]) self.assert_(2**k > n > 2**(k-2)) n -= n >> 15 # check a little farther below the next power of two k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) # note the stronger assertion self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion class MersenneTwister_TestBasicOps(TestBasicOps): gen = random.Random() def test_setstate_first_arg(self): self.assertRaises(ValueError, self.gen.setstate, (1, None, None)) def test_setstate_middle_arg(self): # Wrong type, s/b tuple self.assertRaises(TypeError, self.gen.setstate, (2, None, None)) # Wrong length, s/b 625 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None)) # Wrong type, s/b tuple of 625 ints self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None)) # Last element s/b an int also self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None)) def test_referenceImplementation(self): # Compare the python implementation with results from the original # code. Create 2000 53-bit precision random floats. Compare only # the last ten entries to show that the independent implementations # are tracking. Here is the main() function needed to create the # list of expected random numbers: # void main(void){ # int i; # unsigned long init[4]={61731, 24903, 614, 42143}, length=4; # init_by_array(init, length); # for (i=0; i<2000; i++) { # printf("%.15f ", genrand_res53()); # if (i%5==4) printf("\n"); # } # } expected = [0.45839803073713259, 0.86057815201978782, 0.92848331726782152, 0.35932681119782461, 0.081823493762449573, 0.14332226470169329, 0.084297823823520024, 0.53814864671831453, 0.089215024911993401, 0.78486196105372907] self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): self.assertAlmostEqual(a,e,places=14) def test_strong_reference_implementation(self): # Like test_referenceImplementation, but checks for exact bit-level # equality. This should pass on any box where C double contains # at least 53 bits of precision (the underlying algorithm suffers # no rounding errors -- all results are exact). from math import ldexp expected = [0x0eab3258d2231fL, 0x1b89db315277a5L, 0x1db622a5518016L, 0x0b7f9af0d575bfL, 0x029e4c4db82240L, 0x04961892f5d673L, 0x02b291598e4589L, 0x11388382c15694L, 0x02dad977c9e1feL, 0x191d96d4d334c6L] self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): self.assertEqual(long(ldexp(a, 53)), e) def test_long_seed(self): # This is most interesting to run in debug mode, just to make sure # nothing blows up. Under the covers, a dynamically resized array # is allocated, consuming space proportional to the number of bits # in the seed. Unfortunately, that's a quadratic-time algorithm, # so don't make this horribly big. seed = (1L << (10000 * 8)) - 1 # about 10K bytes self.gen.seed(seed) def test_53_bits_per_float(self): # This should pass whenever a C double has 53 bit precision. span = 2 ** 53 cum = 0 for i in xrange(100): cum |= int(self.gen.random() * span) self.assertEqual(cum, span-1) def test_bigrand(self): # The randrange routine should build-up the required number of bits # in stages so that all bit positions are active. span = 2 ** 500 cum = 0 for i in xrange(100): r = self.gen.randrange(span) self.assert_(0 <= r < span) cum |= r self.assertEqual(cum, span-1) def test_bigrand_ranges(self): for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: start = self.gen.randrange(2 ** i) stop = self.gen.randrange(2 ** (i-2)) if stop <= start: return self.assert_(start <= self.gen.randrange(start, stop) < stop) def test_rangelimits(self): for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: self.assertEqual(set(range(start,stop)), set([self.gen.randrange(start,stop) for i in xrange(100)])) def test_genrandbits(self): # Verify cross-platform repeatability self.gen.seed(1234567) self.assertEqual(self.gen.getrandbits(100), 97904845777343510404718956115L) # Verify ranges for k in xrange(1, 1000): self.assert_(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: cum = 0 for i in xrange(100): cum |= getbits(span) self.assertEqual(cum, 2**span-1) # Verify argument checking self.assertRaises(TypeError, self.gen.getrandbits) self.assertRaises(TypeError, self.gen.getrandbits, 'a') self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) self.assertRaises(ValueError, self.gen.getrandbits, 0) self.assertRaises(ValueError, self.gen.getrandbits, -1) def test_randbelow_logic(self, _log=log, int=int): # check bitcount transition points: 2**i and 2**(i+1)-1 # show that: k = int(1.001 + _log(n, 2)) # is equal to or one greater than the number of bits in n for i in xrange(1, 1000): n = 1L << i # check an exact power of two numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) self.assert_(n == 2**(k-1)) n += n - 1 # check 1 below the next power of two k = int(1.00001 + _log(n, 2)) self.assert_(k in [numbits, numbits+1]) self.assert_(2**k > n > 2**(k-2)) n -= n >> 15 # check a little farther below the next power of two k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) # note the stronger assertion self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion _gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289, 771.3234287757674, -176.6150291498386, 12.50734324009056, -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06) def gamma(z, cof=_gammacoeff, g=7): z -= 1.0 sum = cof[0] for i in xrange(1,len(cof)): sum += cof[i] / (z+i) z += 0.5 return (z+g)**z / exp(z+g) * sqrt(2*pi) * sum class TestDistributions(unittest.TestCase): def test_zeroinputs(self): # Verify that distributions can handle a series of zero inputs' g = random.Random() x = [g.random() for i in xrange(50)] + [0.0]*5 g.random = x[:].pop; g.uniform(1,10) g.random = x[:].pop; g.paretovariate(1.0) g.random = x[:].pop; g.expovariate(1.0) g.random = x[:].pop; g.weibullvariate(1.0, 1.0) g.random = x[:].pop; g.normalvariate(0.0, 1.0) g.random = x[:].pop; g.gauss(0.0, 1.0) g.random = x[:].pop; g.lognormvariate(0.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) g.random = x[:].pop; g.gammavariate(0.01, 1.0) g.random = x[:].pop; g.gammavariate(1.0, 1.0) g.random = x[:].pop; g.gammavariate(200.0, 1.0) g.random = x[:].pop; g.betavariate(3.0, 3.0) def test_avg_std(self): # Use integration to test distribution average and standard deviation. # Only works for distributions which do not consume variates in pairs g = random.Random() N = 5000 x = [i/float(N) for i in xrange(1,N)] for variate, args, mu, sigmasqrd in [ (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12), (g.expovariate, (1.5,), 1/1.5, 1/1.5**2), (g.paretovariate, (5.0,), 5.0/(5.0-1), 5.0/((5.0-1)**2*(5.0-2))), (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0), gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]: g.random = x[:].pop y = [] for i in xrange(len(x)): try: y.append(variate(*args)) except IndexError: pass s1 = s2 = 0 for e in y: s1 += e s2 += (e - mu) ** 2 N = len(y) self.assertAlmostEqual(s1/N, mu, 2) self.assertAlmostEqual(s2/(N-1), sigmasqrd, 2) class TestModule(unittest.TestCase): def testMagicConstants(self): self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141) self.assertAlmostEqual(random.TWOPI, 6.28318530718) self.assertAlmostEqual(random.LOG4, 1.38629436111989) self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627) def test__all__(self): # tests validity but not completeness of the __all__ list self.failUnless(set(random.__all__) <= set(dir(random))) def test_main(verbose=None): testclasses = [WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, TestDistributions, TestModule] try: random.SystemRandom().random() except NotImplementedError: pass else: testclasses.append(SystemRandom_TestBasicOps) test_support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() print counts if __name__ == "__main__": test_main(verbose=True)
Python
#!/usr/bin/env python # UserString is a wrapper around the native builtin string type. # UserString instances should behave similar to builtin string objects. import unittest from test import test_support, string_tests from UserString import UserString class UserStringTest( string_tests.CommonTest, string_tests.MixinStrUnicodeUserStringTest, string_tests.MixinStrStringUserStringTest, string_tests.MixinStrUserStringTest ): type2test = UserString fixargs = lambda self, args: args subclasscheck = False def test_main(): test_support.run_unittest(UserStringTest) if __name__ == "__main__": test_main()
Python
#!/usr/bin/python # # Test suite for Optik. Supplied by Johannes Gijsbers # (taradino@softhome.net) -- translated from the original Optik # test suite to this PyUnit-based version. # # $Id: test_optparse.py,v 1.10 2004/10/27 02:43:25 tim_one Exp $ # import sys import os import copy import unittest from cStringIO import StringIO from pprint import pprint from test import test_support from optparse import make_option, Option, IndentedHelpFormatter, \ TitledHelpFormatter, OptionParser, OptionContainer, OptionGroup, \ SUPPRESS_HELP, SUPPRESS_USAGE, OptionError, OptionConflictError, \ BadOptionError, OptionValueError, Values, _match_abbrev # Do the right thing with boolean values for all known Python versions. try: True, False except NameError: (True, False) = (1, 0) class InterceptedError(Exception): def __init__(self, error_message=None, exit_status=None, exit_message=None): self.error_message = error_message self.exit_status = exit_status self.exit_message = exit_message def __str__(self): return self.error_message or self.exit_message or "intercepted error" class InterceptingOptionParser(OptionParser): def exit(self, status=0, msg=None): raise InterceptedError(exit_status=status, exit_message=msg) def error(self, msg): raise InterceptedError(error_message=msg) class BaseTest(unittest.TestCase): def assertParseOK(self, args, expected_opts, expected_positional_args): """Assert the options are what we expected when parsing arguments. Otherwise, fail with a nicely formatted message. Keyword arguments: args -- A list of arguments to parse with OptionParser. expected_opts -- The options expected. expected_positional_args -- The positional arguments expected. Returns the options and positional args for further testing. """ (options, positional_args) = self.parser.parse_args(args) optdict = vars(options) self.assertEqual(optdict, expected_opts, """ Options are %(optdict)s. Should be %(expected_opts)s. Args were %(args)s.""" % locals()) self.assertEqual(positional_args, expected_positional_args, """ Positional arguments are %(positional_args)s. Should be %(expected_positional_args)s. Args were %(args)s.""" % locals ()) return (options, positional_args) def assertRaises(self, func, args, kwargs, expected_exception, expected_message): """ Assert that the expected exception is raised when calling a function, and that the right error message is included with that exception. Arguments: func -- the function to call args -- positional arguments to `func` kwargs -- keyword arguments to `func` expected_exception -- exception that should be raised expected_output -- output we expect to see Returns the exception raised for further testing. """ if args is None: args = () if kwargs is None: kwargs = {} try: func(*args, **kwargs) except expected_exception, err: actual_message = str(err) self.assertEqual(actual_message, expected_message, """\ expected exception message: '''%(expected_message)s''' actual exception message: '''%(actual_message)s''' """ % locals()) return err else: self.fail("""expected exception %(expected_exception)s not raised called %(func)r with args %(args)r and kwargs %(kwargs)r """ % locals ()) # -- Assertions used in more than one class -------------------- def assertParseFail(self, cmdline_args, expected_output): """ Assert the parser fails with the expected message. Caller must ensure that self.parser is an InterceptingOptionParser. """ try: self.parser.parse_args(cmdline_args) except InterceptedError, err: self.assertEqual(err.error_message, expected_output) else: self.assertFalse("expected parse failure") def assertOutput(self, cmdline_args, expected_output, expected_status=0, expected_error=None): """Assert the parser prints the expected output on stdout.""" save_stdout = sys.stdout try: try: sys.stdout = StringIO() self.parser.parse_args(cmdline_args) finally: output = sys.stdout.getvalue() sys.stdout = save_stdout except InterceptedError, err: self.assertEqual(output, expected_output) self.assertEqual(err.exit_status, expected_status) self.assertEqual(err.exit_message, expected_error) else: self.assertFalse("expected parser.exit()") def assertTypeError(self, func, expected_message, *args): """Assert that TypeError is raised when executing func.""" self.assertRaises(func, args, None, TypeError, expected_message) def assertHelp(self, parser, expected_help): actual_help = parser.format_help() if actual_help != expected_help: raise self.failureException( 'help text failure; expected:\n"' + expected_help + '"; got:\n"' + actual_help + '"\n') # -- Test make_option() aka Option ------------------------------------- # It's not necessary to test correct options here. All the tests in the # parser.parse_args() section deal with those, because they're needed # there. class TestOptionChecks(BaseTest): def setUp(self): self.parser = OptionParser(usage=SUPPRESS_USAGE) def assertOptionError(self, expected_message, args=[], kwargs={}): self.assertRaises(make_option, args, kwargs, OptionError, expected_message) def test_opt_string_empty(self): self.assertTypeError(make_option, "at least one option string must be supplied") def test_opt_string_too_short(self): self.assertOptionError( "invalid option string 'b': must be at least two characters long", ["b"]) def test_opt_string_short_invalid(self): self.assertOptionError( "invalid short option string '--': must be " "of the form -x, (x any non-dash char)", ["--"]) def test_opt_string_long_invalid(self): self.assertOptionError( "invalid long option string '---': " "must start with --, followed by non-dash", ["---"]) def test_attr_invalid(self): d = {'foo': None, 'bar': None} msg = ', '.join(d.keys()) self.assertOptionError( "option -b: invalid keyword arguments: %s" % msg, ["-b"], d) def test_action_invalid(self): self.assertOptionError( "option -b: invalid action: 'foo'", ["-b"], {'action': 'foo'}) def test_type_invalid(self): self.assertOptionError( "option -b: invalid option type: 'foo'", ["-b"], {'type': 'foo'}) self.assertOptionError( "option -b: invalid option type: 'tuple'", ["-b"], {'type': tuple}) def test_no_type_for_action(self): self.assertOptionError( "option -b: must not supply a type for action 'count'", ["-b"], {'action': 'count', 'type': 'int'}) def test_no_choices_list(self): self.assertOptionError( "option -b/--bad: must supply a list of " "choices for type 'choice'", ["-b", "--bad"], {'type': "choice"}) def test_bad_choices_list(self): typename = type('').__name__ self.assertOptionError( "option -b/--bad: choices must be a list of " "strings ('%s' supplied)" % typename, ["-b", "--bad"], {'type': "choice", 'choices':"bad choices"}) def test_no_choices_for_type(self): self.assertOptionError( "option -b: must not supply choices for type 'int'", ["-b"], {'type': 'int', 'choices':"bad"}) def test_no_const_for_action(self): self.assertOptionError( "option -b: 'const' must not be supplied for action 'store'", ["-b"], {'action': 'store', 'const': 1}) def test_no_nargs_for_action(self): self.assertOptionError( "option -b: 'nargs' must not be supplied for action 'count'", ["-b"], {'action': 'count', 'nargs': 2}) def test_callback_not_callable(self): self.assertOptionError( "option -b: callback not callable: 'foo'", ["-b"], {'action': 'callback', 'callback': 'foo'}) def dummy(self): pass def test_callback_args_no_tuple(self): self.assertOptionError( "option -b: callback_args, if supplied, " "must be a tuple: not 'foo'", ["-b"], {'action': 'callback', 'callback': self.dummy, 'callback_args': 'foo'}) def test_callback_kwargs_no_dict(self): self.assertOptionError( "option -b: callback_kwargs, if supplied, " "must be a dict: not 'foo'", ["-b"], {'action': 'callback', 'callback': self.dummy, 'callback_kwargs': 'foo'}) def test_no_callback_for_action(self): self.assertOptionError( "option -b: callback supplied ('foo') for non-callback option", ["-b"], {'action': 'store', 'callback': 'foo'}) def test_no_callback_args_for_action(self): self.assertOptionError( "option -b: callback_args supplied for non-callback option", ["-b"], {'action': 'store', 'callback_args': 'foo'}) def test_no_callback_kwargs_for_action(self): self.assertOptionError( "option -b: callback_kwargs supplied for non-callback option", ["-b"], {'action': 'store', 'callback_kwargs': 'foo'}) class TestOptionParser(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("-v", "--verbose", "-n", "--noisy", action="store_true", dest="verbose") self.parser.add_option("-q", "--quiet", "--silent", action="store_false", dest="verbose") def test_add_option_no_Option(self): self.assertTypeError(self.parser.add_option, "not an Option instance: None", None) def test_add_option_invalid_arguments(self): self.assertTypeError(self.parser.add_option, "invalid arguments", None, None) def test_get_option(self): opt1 = self.parser.get_option("-v") self.assert_(isinstance(opt1, Option)) self.assertEqual(opt1._short_opts, ["-v", "-n"]) self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"]) self.assertEqual(opt1.action, "store_true") self.assertEqual(opt1.dest, "verbose") def test_get_option_equals(self): opt1 = self.parser.get_option("-v") opt2 = self.parser.get_option("--verbose") opt3 = self.parser.get_option("-n") opt4 = self.parser.get_option("--noisy") self.assert_(opt1 is opt2 is opt3 is opt4) def test_has_option(self): self.assert_(self.parser.has_option("-v")) self.assert_(self.parser.has_option("--verbose")) def assert_removed(self): self.assert_(self.parser.get_option("-v") is None) self.assert_(self.parser.get_option("--verbose") is None) self.assert_(self.parser.get_option("-n") is None) self.assert_(self.parser.get_option("--noisy") is None) self.failIf(self.parser.has_option("-v")) self.failIf(self.parser.has_option("--verbose")) self.failIf(self.parser.has_option("-n")) self.failIf(self.parser.has_option("--noisy")) self.assert_(self.parser.has_option("-q")) self.assert_(self.parser.has_option("--silent")) def test_remove_short_opt(self): self.parser.remove_option("-n") self.assert_removed() def test_remove_long_opt(self): self.parser.remove_option("--verbose") self.assert_removed() def test_remove_nonexistent(self): self.assertRaises(self.parser.remove_option, ('foo',), None, ValueError, "no such option 'foo'") class TestOptionValues(BaseTest): def setUp(self): pass def test_basics(self): values = Values() self.assertEqual(vars(values), {}) self.assertEqual(values, {}) self.assertNotEqual(values, {"foo": "bar"}) self.assertNotEqual(values, "") dict = {"foo": "bar", "baz": 42} values = Values(defaults=dict) self.assertEqual(vars(values), dict) self.assertEqual(values, dict) self.assertNotEqual(values, {"foo": "bar"}) self.assertNotEqual(values, {}) self.assertNotEqual(values, "") self.assertNotEqual(values, []) class TestTypeAliases(BaseTest): def setUp(self): self.parser = OptionParser() def test_type_aliases(self): self.parser.add_option("-x", type=int) self.parser.add_option("-s", type=str) self.parser.add_option("-t", type="str") self.assertEquals(self.parser.get_option("-x").type, "int") self.assertEquals(self.parser.get_option("-s").type, "string") self.assertEquals(self.parser.get_option("-t").type, "string") # Custom type for testing processing of default values. _time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 } def _check_duration(option, opt, value): try: if value[-1].isdigit(): return int(value) else: return int(value[:-1]) * _time_units[value[-1]] except ValueError, IndexError: raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) class DurationOption(Option): TYPES = Option.TYPES + ('duration',) TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER) TYPE_CHECKER['duration'] = _check_duration class TestDefaultValues(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("-v", "--verbose", default=True) self.parser.add_option("-q", "--quiet", dest='verbose') self.parser.add_option("-n", type="int", default=37) self.parser.add_option("-m", type="int") self.parser.add_option("-s", default="foo") self.parser.add_option("-t") self.parser.add_option("-u", default=None) self.expected = { 'verbose': True, 'n': 37, 'm': None, 's': "foo", 't': None, 'u': None } def test_basic_defaults(self): self.assertEqual(self.parser.get_default_values(), self.expected) def test_mixed_defaults_post(self): self.parser.set_defaults(n=42, m=-100) self.expected.update({'n': 42, 'm': -100}) self.assertEqual(self.parser.get_default_values(), self.expected) def test_mixed_defaults_pre(self): self.parser.set_defaults(x="barf", y="blah") self.parser.add_option("-x", default="frob") self.parser.add_option("-y") self.expected.update({'x': "frob", 'y': "blah"}) self.assertEqual(self.parser.get_default_values(), self.expected) self.parser.remove_option("-y") self.parser.add_option("-y", default=None) self.expected.update({'y': None}) self.assertEqual(self.parser.get_default_values(), self.expected) def test_process_default(self): self.parser.option_class = DurationOption self.parser.add_option("-d", type="duration", default=300) self.parser.add_option("-e", type="duration", default="6m") self.parser.set_defaults(n="42") self.expected.update({'d': 300, 'e': 360, 'n': 42}) self.assertEqual(self.parser.get_default_values(), self.expected) self.parser.set_process_default_values(False) self.expected.update({'d': 300, 'e': "6m", 'n': "42"}) self.assertEqual(self.parser.get_default_values(), self.expected) class TestProgName(BaseTest): """ Test that %prog expands to the right thing in usage, version, and help strings. """ def assertUsage(self, parser, expected_usage): self.assertEqual(parser.get_usage(), expected_usage) def assertVersion(self, parser, expected_version): self.assertEqual(parser.get_version(), expected_version) def test_default_progname(self): # Make sure that program name taken from sys.argv[0] by default. save_argv = sys.argv[:] try: sys.argv[0] = os.path.join("foo", "bar", "baz.py") parser = OptionParser("usage: %prog ...", version="%prog 1.2") expected_usage = "usage: baz.py ...\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "baz.py 1.2") self.assertHelp(parser, expected_usage + "\n" + "options:\n" " --version show program's version number and exit\n" " -h, --help show this help message and exit\n") finally: sys.argv[:] = save_argv def test_custom_progname(self): parser = OptionParser(prog="thingy", version="%prog 0.1", usage="%prog arg arg") parser.remove_option("-h") parser.remove_option("--version") expected_usage = "usage: thingy arg arg\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "thingy 0.1") self.assertHelp(parser, expected_usage + "\n") class TestExpandDefaults(BaseTest): def setUp(self): self.parser = OptionParser(prog="test") self.help_prefix = """\ usage: test [options] options: -h, --help show this help message and exit """ self.file_help = "read from FILE [default: %default]" self.expected_help_file = self.help_prefix + \ " -f FILE, --file=FILE read from FILE [default: foo.txt]\n" self.expected_help_none = self.help_prefix + \ " -f FILE, --file=FILE read from FILE [default: none]\n" def test_option_default(self): self.parser.add_option("-f", "--file", default="foo.txt", help=self.file_help) self.assertHelp(self.parser, self.expected_help_file) def test_parser_default_1(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_default('file', "foo.txt") self.assertHelp(self.parser, self.expected_help_file) def test_parser_default_2(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_defaults(file="foo.txt") self.assertHelp(self.parser, self.expected_help_file) def test_no_default(self): self.parser.add_option("-f", "--file", help=self.file_help) self.assertHelp(self.parser, self.expected_help_none) def test_default_none_1(self): self.parser.add_option("-f", "--file", default=None, help=self.file_help) self.assertHelp(self.parser, self.expected_help_none) def test_default_none_2(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_defaults(file=None) self.assertHelp(self.parser, self.expected_help_none) def test_float_default(self): self.parser.add_option( "-p", "--prob", help="blow up with probability PROB [default: %default]") self.parser.set_defaults(prob=0.43) expected_help = self.help_prefix + \ " -p PROB, --prob=PROB blow up with probability PROB [default: 0.43]\n" self.assertHelp(self.parser, expected_help) def test_alt_expand(self): self.parser.add_option("-f", "--file", default="foo.txt", help="read from FILE [default: *DEFAULT*]") self.parser.formatter.default_tag = "*DEFAULT*" self.assertHelp(self.parser, self.expected_help_file) def test_no_expand(self): self.parser.add_option("-f", "--file", default="foo.txt", help="read from %default file") self.parser.formatter.default_tag = None expected_help = self.help_prefix + \ " -f FILE, --file=FILE read from %default file\n" self.assertHelp(self.parser, expected_help) # -- Test parser.parse_args() ------------------------------------------ class TestStandard(BaseTest): def setUp(self): options = [make_option("-a", type="string"), make_option("-b", "--boo", type="int", dest='boo'), make_option("--foo", action="append")] self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list=options) def test_required_value(self): self.assertParseFail(["-a"], "-a option requires an argument") def test_invalid_integer(self): self.assertParseFail(["-b", "5x"], "option -b: invalid integer value: '5x'") def test_no_such_option(self): self.assertParseFail(["--boo13"], "no such option: --boo13") def test_long_invalid_integer(self): self.assertParseFail(["--boo=x5"], "option --boo: invalid integer value: 'x5'") def test_empty(self): self.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, []) def test_shortopt_empty_longopt_append(self): self.assertParseOK(["-a", "", "--foo=blah", "--foo="], {'a': "", 'boo': None, 'foo': ["blah", ""]}, []) def test_long_option_append(self): self.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"], {'a': None, 'boo': None, 'foo': ["bar", "", "x"]}, []) def test_option_argument_joined(self): self.assertParseOK(["-abc"], {'a': "bc", 'boo': None, 'foo': None}, []) def test_option_argument_split(self): self.assertParseOK(["-a", "34"], {'a': "34", 'boo': None, 'foo': None}, []) def test_option_argument_joined_integer(self): self.assertParseOK(["-b34"], {'a': None, 'boo': 34, 'foo': None}, []) def test_option_argument_split_negative_integer(self): self.assertParseOK(["-b", "-5"], {'a': None, 'boo': -5, 'foo': None}, []) def test_long_option_argument_joined(self): self.assertParseOK(["--boo=13"], {'a': None, 'boo': 13, 'foo': None}, []) def test_long_option_argument_split(self): self.assertParseOK(["--boo", "111"], {'a': None, 'boo': 111, 'foo': None}, []) def test_long_option_short_option(self): self.assertParseOK(["--foo=bar", "-axyz"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []) def test_abbrev_long_option(self): self.assertParseOK(["--f=bar", "-axyz"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []) def test_defaults(self): (options, args) = self.parser.parse_args([]) defaults = self.parser.get_default_values() self.assertEqual(vars(defaults), vars(options)) def test_ambiguous_option(self): self.parser.add_option("--foz", action="store", type="string", dest="foo") possibilities = ", ".join({"--foz": None, "--foo": None}.keys()) self.assertParseFail(["--f=bar"], "ambiguous option: --f (%s?)" % possibilities) def test_short_and_long_option_split(self): self.assertParseOK(["-a", "xyz", "--foo", "bar"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []), def test_short_option_split_long_option_append(self): self.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"], {'a': None, 'boo': 123, 'foo': ["bar", "baz"]}, []) def test_short_option_split_one_positional_arg(self): self.assertParseOK(["-a", "foo", "bar"], {'a': "foo", 'boo': None, 'foo': None}, ["bar"]), def test_short_option_consumes_separator(self): self.assertParseOK(["-a", "--", "foo", "bar"], {'a': "--", 'boo': None, 'foo': None}, ["foo", "bar"]), def test_short_option_joined_and_separator(self): self.assertParseOK(["-ab", "--", "--foo", "bar"], {'a': "b", 'boo': None, 'foo': None}, ["--foo", "bar"]), def test_invalid_option_becomes_positional_arg(self): self.assertParseOK(["-ab", "-", "--foo", "bar"], {'a': "b", 'boo': None, 'foo': ["bar"]}, ["-"]) def test_no_append_versus_append(self): self.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"], {'a': None, 'boo': 5, 'foo': ["bar", "baz"]}, []) def test_option_consumes_optionlike_string(self): self.assertParseOK(["-a", "-b3"], {'a': "-b3", 'boo': None, 'foo': None}, []) class TestBool(BaseTest): def setUp(self): options = [make_option("-v", "--verbose", action="store_true", dest="verbose", default=''), make_option("-q", "--quiet", action="store_false", dest="verbose")] self.parser = OptionParser(option_list = options) def test_bool_default(self): self.assertParseOK([], {'verbose': ''}, []) def test_bool_false(self): (options, args) = self.assertParseOK(["-q"], {'verbose': 0}, []) if hasattr(__builtins__, 'False'): self.failUnless(options.verbose is False) def test_bool_true(self): (options, args) = self.assertParseOK(["-v"], {'verbose': 1}, []) if hasattr(__builtins__, 'True'): self.failUnless(options.verbose is True) def test_bool_flicker_on_and_off(self): self.assertParseOK(["-qvq", "-q", "-v"], {'verbose': 1}, []) class TestChoice(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-c", action="store", type="choice", dest="choice", choices=["one", "two", "three"]) def test_valid_choice(self): self.assertParseOK(["-c", "one", "xyz"], {'choice': 'one'}, ["xyz"]) def test_invalid_choice(self): self.assertParseFail(["-c", "four", "abc"], "option -c: invalid choice: 'four' " "(choose from 'one', 'two', 'three')") def test_add_choice_option(self): self.parser.add_option("-d", "--default", choices=["four", "five", "six"]) opt = self.parser.get_option("-d") self.assertEqual(opt.type, "choice") self.assertEqual(opt.action, "store") class TestCount(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.v_opt = make_option("-v", action="count", dest="verbose") self.parser.add_option(self.v_opt) self.parser.add_option("--verbose", type="int", dest="verbose") self.parser.add_option("-q", "--quiet", action="store_const", dest="verbose", const=0) def test_empty(self): self.assertParseOK([], {'verbose': None}, []) def test_count_one(self): self.assertParseOK(["-v"], {'verbose': 1}, []) def test_count_three(self): self.assertParseOK(["-vvv"], {'verbose': 3}, []) def test_count_three_apart(self): self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, []) def test_count_override_amount(self): self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, []) def test_count_override_quiet(self): self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, []) def test_count_overriding(self): self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"], {'verbose': 1}, []) def test_count_interspersed_args(self): self.assertParseOK(["--quiet", "3", "-v"], {'verbose': 1}, ["3"]) def test_count_no_interspersed_args(self): self.parser.disable_interspersed_args() self.assertParseOK(["--quiet", "3", "-v"], {'verbose': 0}, ["3", "-v"]) def test_count_no_such_option(self): self.assertParseFail(["-q3", "-v"], "no such option: -3") def test_count_option_no_value(self): self.assertParseFail(["--quiet=3", "-v"], "--quiet option does not take a value") def test_count_with_default(self): self.parser.set_default('verbose', 0) self.assertParseOK([], {'verbose':0}, []) def test_count_overriding_default(self): self.parser.set_default('verbose', 0) self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"], {'verbose': 1}, []) class TestMultipleArgs(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-p", "--point", action="store", nargs=3, type="float", dest="point") def test_nargs_with_positional_args(self): self.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"], {'point': (1.0, 2.5, -4.3)}, ["foo", "xyz"]) def test_nargs_long_opt(self): self.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"], {'point': (-1.0, 2.5, -0.0)}, ["xyz"]) def test_nargs_invalid_float_value(self): self.assertParseFail(["-p", "1.0", "2x", "3.5"], "option -p: " "invalid floating-point value: '2x'") def test_nargs_required_values(self): self.assertParseFail(["--point", "1.0", "3.5"], "--point option requires 3 arguments") class TestMultipleArgsAppend(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-p", "--point", action="store", nargs=3, type="float", dest="point") self.parser.add_option("-f", "--foo", action="append", nargs=2, type="int", dest="foo") def test_nargs_append(self): self.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"], {'point': None, 'foo': [(4, -3), (1, 666)]}, ["blah"]) def test_nargs_append_required_values(self): self.assertParseFail(["-f4,3"], "-f option requires 2 arguments") def test_nargs_append_simple(self): self.assertParseOK(["--foo=3", "4"], {'point': None, 'foo':[(3, 4)]}, []) class TestVersion(BaseTest): def test_version(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, version="%prog 0.1") save_argv = sys.argv[:] try: sys.argv[0] = os.path.join(os.curdir, "foo", "bar") self.assertOutput(["--version"], "bar 0.1\n") finally: sys.argv[:] = save_argv def test_no_version(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.assertParseFail(["--version"], "no such option: --version") # -- Test conflicting default values and parser.parse_args() ----------- class TestConflictingDefaults(BaseTest): """Conflicting default values: the last one should win.""" def setUp(self): self.parser = OptionParser(option_list=[ make_option("-v", action="store_true", dest="verbose", default=1)]) def test_conflict_default(self): self.parser.add_option("-q", action="store_false", dest="verbose", default=0) self.assertParseOK([], {'verbose': 0}, []) def test_conflict_default_none(self): self.parser.add_option("-q", action="store_false", dest="verbose", default=None) self.assertParseOK([], {'verbose': None}, []) class TestOptionGroup(BaseTest): def setUp(self): self.parser = OptionParser(usage=SUPPRESS_USAGE) def test_option_group_create_instance(self): group = OptionGroup(self.parser, "Spam") self.parser.add_option_group(group) group.add_option("--spam", action="store_true", help="spam spam spam spam") self.assertParseOK(["--spam"], {'spam': 1}, []) def test_add_group_no_group(self): self.assertTypeError(self.parser.add_option_group, "not an OptionGroup instance: None", None) def test_add_group_invalid_arguments(self): self.assertTypeError(self.parser.add_option_group, "invalid arguments", None, None) def test_add_group_wrong_parser(self): group = OptionGroup(self.parser, "Spam") group.parser = OptionParser() self.assertRaises(self.parser.add_option_group, (group,), None, ValueError, "invalid OptionGroup (wrong parser)") def test_group_manipulate(self): group = self.parser.add_option_group("Group 2", description="Some more options") group.set_title("Bacon") group.add_option("--bacon", type="int") self.assert_(self.parser.get_option_group("--bacon"), group) # -- Test extending and parser.parse_args() ---------------------------- class TestExtendAddTypes(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_class=self.MyOption) self.parser.add_option("-a", None, type="string", dest="a") self.parser.add_option("-f", "--file", type="file", dest="file") class MyOption (Option): def check_file (option, opt, value): if not os.path.exists(value): raise OptionValueError("%s: file does not exist" % value) elif not os.path.isfile(value): raise OptionValueError("%s: not a regular file" % value) return value TYPES = Option.TYPES + ("file",) TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER) TYPE_CHECKER["file"] = check_file def test_extend_file(self): open(test_support.TESTFN, "w").close() self.assertParseOK(["--file", test_support.TESTFN, "-afoo"], {'file': test_support.TESTFN, 'a': 'foo'}, []) os.unlink(test_support.TESTFN) def test_extend_file_nonexistent(self): self.assertParseFail(["--file", test_support.TESTFN, "-afoo"], "%s: file does not exist" % test_support.TESTFN) def test_file_irregular(self): os.mkdir(test_support.TESTFN) self.assertParseFail(["--file", test_support.TESTFN, "-afoo"], "%s: not a regular file" % test_support.TESTFN) os.rmdir(test_support.TESTFN) class TestExtendAddActions(BaseTest): def setUp(self): options = [self.MyOption("-a", "--apple", action="extend", type="string", dest="apple")] self.parser = OptionParser(option_list=options) class MyOption (Option): ACTIONS = Option.ACTIONS + ("extend",) STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) def take_action (self, action, dest, opt, value, values, parser): if action == "extend": lvalue = value.split(",") values.ensure_value(dest, []).extend(lvalue) else: Option.take_action(self, action, dest, opt, parser, value, values) def test_extend_add_action(self): self.assertParseOK(["-afoo,bar", "--apple=blah"], {'apple': ["foo", "bar", "blah"]}, []) def test_extend_add_action_normal(self): self.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"], {'apple': ["foo", "bar", "x", "y"]}, []) # -- Test callbacks and parser.parse_args() ---------------------------- class TestCallback(BaseTest): def setUp(self): options = [make_option("-x", None, action="callback", callback=self.process_opt), make_option("-f", "--file", action="callback", callback=self.process_opt, type="string", dest="filename")] self.parser = OptionParser(option_list=options) def process_opt(self, option, opt, value, parser_): if opt == "-x": self.assertEqual(option._short_opts, ["-x"]) self.assertEqual(option._long_opts, []) self.assert_(parser_ is self.parser) self.assert_(value is None) self.assertEqual(vars(parser_.values), {'filename': None}) parser_.values.x = 42 elif opt == "--file": self.assertEqual(option._short_opts, ["-f"]) self.assertEqual(option._long_opts, ["--file"]) self.assert_(parser_ is self.parser) self.assertEqual(value, "foo") self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42}) setattr(parser_.values, option.dest, value) else: self.fail("Unknown option %r in process_opt." % opt) def test_callback(self): self.assertParseOK(["-x", "--file=foo"], {'filename': "foo", 'x': 42}, []) def test_callback_help(self): # This test was prompted by SF bug #960515 -- the point is # not to inspect the help text, just to make sure that # format_help() doesn't crash. parser = OptionParser(usage=SUPPRESS_USAGE) parser.remove_option("-h") parser.add_option("-t", "--test", action="callback", callback=lambda: None, type="string", help="foo") expected_help = ("options:\n" " -t TEST, --test=TEST foo\n") self.assertHelp(parser, expected_help) class TestCallbackExtraArgs(BaseTest): def setUp(self): options = [make_option("-p", "--point", action="callback", callback=self.process_tuple, callback_args=(3, int), type="string", dest="points", default=[])] self.parser = OptionParser(option_list=options) def process_tuple (self, option, opt, value, parser_, len, type): self.assertEqual(len, 3) self.assert_(type is int) if opt == "-p": self.assertEqual(value, "1,2,3") elif opt == "--point": self.assertEqual(value, "4,5,6") value = tuple(map(type, value.split(","))) getattr(parser_.values, option.dest).append(value) def test_callback_extra_args(self): self.assertParseOK(["-p1,2,3", "--point", "4,5,6"], {'points': [(1,2,3), (4,5,6)]}, []) class TestCallbackMeddleArgs(BaseTest): def setUp(self): options = [make_option(str(x), action="callback", callback=self.process_n, dest='things') for x in range(-1, -6, -1)] self.parser = OptionParser(option_list=options) # Callback that meddles in rargs, largs def process_n (self, option, opt, value, parser_): # option is -3, -5, etc. nargs = int(opt[1:]) rargs = parser_.rargs if len(rargs) < nargs: self.fail("Expected %d arguments for %s option." % (nargs, opt)) dest = parser_.values.ensure_value(option.dest, []) dest.append(tuple(rargs[0:nargs])) parser_.largs.append(nargs) del rargs[0:nargs] def test_callback_meddle_args(self): self.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"], {'things': [("foo",), ("bar", "baz", "qux")]}, [1, 3]) def test_callback_meddle_args_separator(self): self.assertParseOK(["-2", "foo", "--"], {'things': [('foo', '--')]}, [2]) class TestCallbackManyArgs(BaseTest): def setUp(self): options = [make_option("-a", "--apple", action="callback", nargs=2, callback=self.process_many, type="string"), make_option("-b", "--bob", action="callback", nargs=3, callback=self.process_many, type="int")] self.parser = OptionParser(option_list=options) def process_many (self, option, opt, value, parser_): if opt == "-a": self.assertEqual(value, ("foo", "bar")) elif opt == "--apple": self.assertEqual(value, ("ding", "dong")) elif opt == "-b": self.assertEqual(value, (1, 2, 3)) elif opt == "--bob": self.assertEqual(value, (-666, 42, 0)) def test_many_args(self): self.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong", "-b", "1", "2", "3", "--bob", "-666", "42", "0"], {"apple": None, "bob": None}, []) class TestCallbackCheckAbbrev(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("--foo-bar", action="callback", callback=self.check_abbrev) def check_abbrev (self, option, opt, value, parser): self.assertEqual(opt, "--foo-bar") def test_abbrev_callback_expansion(self): self.assertParseOK(["--foo"], {}, []) class TestCallbackVarArgs(BaseTest): def setUp(self): options = [make_option("-a", type="int", nargs=2, dest="a"), make_option("-b", action="store_true", dest="b"), make_option("-c", "--callback", action="callback", callback=self.variable_args, dest="c")] self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list=options) def variable_args (self, option, opt, value, parser): self.assert_(value is None) done = 0 value = [] rargs = parser.rargs while rargs: arg = rargs[0] if ((arg[:2] == "--" and len(arg) > 2) or (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): break else: value.append(arg) del rargs[0] setattr(parser.values, option.dest, value) def test_variable_args(self): self.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"], {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]}, []) def test_consume_separator_stop_at_option(self): self.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"], {'a': None, 'b': True, 'c': ["37", "--", "xxx"]}, ["hello"]) def test_positional_arg_and_variable_args(self): self.assertParseOK(["hello", "-c", "foo", "-", "bar"], {'a': None, 'b': None, 'c':["foo", "-", "bar"]}, ["hello"]) def test_stop_at_option(self): self.assertParseOK(["-c", "foo", "-b"], {'a': None, 'b': True, 'c': ["foo"]}, []) def test_stop_at_invalid_option(self): self.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5") # -- Test conflict handling and parser.parse_args() -------------------- class ConflictBase(BaseTest): def setUp(self): options = [make_option("-v", "--verbose", action="count", dest="verbose", help="increment verbosity")] self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list=options) def show_version (self, option, opt, value, parser): parser.values.show_version = 1 class TestConflict(ConflictBase): """Use the default conflict resolution for Optik 1.2: error.""" def assert_conflict_error(self, func): err = self.assertRaises( func, ("-v", "--version"), {'action' : "callback", 'callback' : self.show_version, 'help' : "show version"}, OptionConflictError, "option -v/--version: conflicting option string(s): -v") self.assertEqual(err.msg, "conflicting option string(s): -v") self.assertEqual(err.option_id, "-v/--version") def test_conflict_error(self): self.assert_conflict_error(self.parser.add_option) def test_conflict_error_group(self): group = OptionGroup(self.parser, "Group 1") self.assert_conflict_error(group.add_option) def test_no_such_conflict_handler(self): self.assertRaises( self.parser.set_conflict_handler, ('foo',), None, ValueError, "invalid conflict_resolution value 'foo'") class TestConflictResolve(ConflictBase): def setUp(self): ConflictBase.setUp(self) self.parser.set_conflict_handler("resolve") self.parser.add_option("-v", "--version", action="callback", callback=self.show_version, help="show version") def test_conflict_resolve(self): v_opt = self.parser.get_option("-v") verbose_opt = self.parser.get_option("--verbose") version_opt = self.parser.get_option("--version") self.assert_(v_opt is version_opt) self.assert_(v_opt is not verbose_opt) self.assertEqual(v_opt._long_opts, ["--version"]) self.assertEqual(version_opt._short_opts, ["-v"]) self.assertEqual(version_opt._long_opts, ["--version"]) self.assertEqual(verbose_opt._short_opts, []) self.assertEqual(verbose_opt._long_opts, ["--verbose"]) def test_conflict_resolve_help(self): self.assertOutput(["-h"], """\ options: --verbose increment verbosity -h, --help show this help message and exit -v, --version show version """) def test_conflict_resolve_short_opt(self): self.assertParseOK(["-v"], {'verbose': None, 'show_version': 1}, []) def test_conflict_resolve_long_opt(self): self.assertParseOK(["--verbose"], {'verbose': 1}, []) def test_conflict_resolve_long_opts(self): self.assertParseOK(["--verbose", "--version"], {'verbose': 1, 'show_version': 1}, []) class TestConflictOverride(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.set_conflict_handler("resolve") self.parser.add_option("-n", "--dry-run", action="store_true", dest="dry_run", help="don't do anything") self.parser.add_option("--dry-run", "-n", action="store_const", const=42, dest="dry_run", help="dry run mode") def test_conflict_override_opts(self): opt = self.parser.get_option("--dry-run") self.assertEqual(opt._short_opts, ["-n"]) self.assertEqual(opt._long_opts, ["--dry-run"]) def test_conflict_override_help(self): self.assertOutput(["-h"], """\ options: -h, --help show this help message and exit -n, --dry-run dry run mode """) def test_conflict_override_args(self): self.assertParseOK(["-n"], {'dry_run': 42}, []) # -- Other testing. ---------------------------------------------------- _expected_help_basic = """\ usage: bar.py [options] options: -a APPLE throw APPLEs at basket -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing -h, --help show this help message and exit """ _expected_help_long_opts_first = """\ usage: bar.py [options] options: -a APPLE throw APPLEs at basket --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing --help, -h show this help message and exit """ _expected_help_title_formatter = """\ Usage ===== bar.py [options] options ======= -a APPLE throw APPLEs at basket --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing --help, -h show this help message and exit """ _expected_help_short_lines = """\ usage: bar.py [options] options: -a APPLE throw APPLEs at basket -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing -h, --help show this help message and exit """ class TestHelp(BaseTest): def setUp(self): self.parser = self.make_parser(80) def make_parser(self, columns): options = [ make_option("-a", type="string", dest='a', metavar="APPLE", help="throw APPLEs at basket"), make_option("-b", "--boo", type="int", dest='boo', metavar="NUM", help= "shout \"boo!\" NUM times (in order to frighten away " "all the evil spirits that cause trouble and mayhem)"), make_option("--foo", action="append", type="string", dest='foo', help="store FOO in the foo list for later fooing"), ] os.environ['COLUMNS'] = str(columns) return InterceptingOptionParser(option_list=options) def assertHelpEquals(self, expected_output): save_argv = sys.argv[:] try: # Make optparse believe bar.py is being executed. sys.argv[0] = os.path.join("foo", "bar.py") self.assertOutput(["-h"], expected_output) finally: sys.argv[:] = save_argv def test_help(self): self.assertHelpEquals(_expected_help_basic) def test_help_old_usage(self): self.parser.set_usage("usage: %prog [options]") self.assertHelpEquals(_expected_help_basic) def test_help_long_opts_first(self): self.parser.formatter.short_first = 0 self.assertHelpEquals(_expected_help_long_opts_first) def test_help_title_formatter(self): self.parser.formatter = TitledHelpFormatter() self.assertHelpEquals(_expected_help_title_formatter) def test_wrap_columns(self): # Ensure that wrapping respects $COLUMNS environment variable. # Need to reconstruct the parser, since that's the only time # we look at $COLUMNS. self.parser = self.make_parser(60) self.assertHelpEquals(_expected_help_short_lines) def test_help_description_groups(self): self.parser.set_description( "This is the program description for %prog. %prog has " "an option group as well as single options.") group = OptionGroup( self.parser, "Dangerous Options", "Caution: use of these options is at your own risk. " "It is believed that some of them bite.") group.add_option("-g", action="store_true", help="Group option.") self.parser.add_option_group(group) self.assertHelpEquals("""\ usage: bar.py [options] This is the program description for bar.py. bar.py has an option group as well as single options. options: -a APPLE throw APPLEs at basket -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing -h, --help show this help message and exit Dangerous Options: Caution: use of these options is at your own risk. It is believed that some of them bite. -g Group option. """) class TestMatchAbbrev(BaseTest): def test_match_abbrev(self): self.assertEqual(_match_abbrev("--f", {"--foz": None, "--foo": None, "--fie": None, "--f": None}), "--f") def test_match_abbrev_error(self): s = "--f" wordmap = {"--foz": None, "--foo": None, "--fie": None} possibilities = ", ".join(wordmap.keys()) self.assertRaises( _match_abbrev, (s, wordmap), None, BadOptionError, "ambiguous option: --f (%s?)" % possibilities) def _testclasses(): mod = sys.modules[__name__] return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')] def suite(): suite = unittest.TestSuite() for testclass in _testclasses(): suite.addTest(unittest.makeSuite(testclass)) return suite def test_main(): test_support.run_suite(suite()) if __name__ == '__main__': unittest.main()
Python
#! /usr/bin/env python """Test the arraymodule. Roger E. Masse """ import unittest from test import test_support #from weakref import proxy import array, cStringIO, math tests = [] # list to accumulate all tests typecodes = "cubBhHiIlLfd" class BadConstructorTest(unittest.TestCase): def test_constructor(self): self.assertRaises(TypeError, array.array) self.assertRaises(TypeError, array.array, spam=42) self.assertRaises(TypeError, array.array, 'xx') self.assertRaises(ValueError, array.array, 'x') tests.append(BadConstructorTest) class BaseTest(unittest.TestCase): # Required class attributes (provided by subclasses # typecode: the typecode to test # example: an initializer usable in the constructor for this type # smallerexample: the same length as example, but smaller # biggerexample: the same length as example, but bigger # outside: An entry that is not in example # minitemsize: the minimum guaranteed itemsize def assertEntryEqual(self, entry1, entry2): self.assertEqual(entry1, entry2) def badtypecode(self): # Return a typecode that is different from our own return typecodes[(typecodes.index(self.typecode)+1) % len(typecodes)] def test_constructor(self): a = array.array(self.typecode) self.assertEqual(a.typecode, self.typecode) self.assert_(a.itemsize>=self.minitemsize) self.assertRaises(TypeError, array.array, self.typecode, None) def test_len(self): a = array.array(self.typecode) a.append(self.example[0]) self.assertEqual(len(a), 1) a = array.array(self.typecode, self.example) self.assertEqual(len(a), len(self.example)) def test_buffer_info(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.buffer_info, 42) bi = a.buffer_info() self.assert_(isinstance(bi, tuple)) self.assertEqual(len(bi), 2) self.assert_(isinstance(bi[0], int)) self.assert_(isinstance(bi[1], int)) self.assertEqual(bi[1], len(a)) def test_byteswap(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.byteswap, 42) if a.itemsize in (1, 2, 4, 8): b = array.array(self.typecode, self.example) b.byteswap() if a.itemsize==1: self.assertEqual(a, b) else: self.assertNotEqual(a, b) b.byteswap() self.assertEqual(a, b) def test_copy(self): import copy a = array.array(self.typecode, self.example) b = copy.copy(a) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) def test_insert(self): a = array.array(self.typecode, self.example) a.insert(0, self.example[0]) self.assertEqual(len(a), 1+len(self.example)) self.assertEqual(a[0], a[1]) self.assertRaises(TypeError, a.insert) self.assertRaises(TypeError, a.insert, None) self.assertRaises(TypeError, a.insert, 0, None) a = array.array(self.typecode, self.example) a.insert(-1, self.example[0]) self.assertEqual( a, array.array( self.typecode, self.example[:-1] + self.example[:1] + self.example[-1:] ) ) a = array.array(self.typecode, self.example) a.insert(-1000, self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example) ) a = array.array(self.typecode, self.example) a.insert(1000, self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example + self.example[:1]) ) def test_tofromfile(self): a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) self.assertRaises(TypeError, a.tofile, cStringIO.StringIO()) f = open(test_support.TESTFN, 'wb') try: a.tofile(f) f.close() b = array.array(self.typecode) f = open(test_support.TESTFN, 'rb') self.assertRaises(TypeError, b.fromfile) self.assertRaises( TypeError, b.fromfile, cStringIO.StringIO(), len(self.example) ) b.fromfile(f, len(self.example)) self.assertEqual(b, array.array(self.typecode, self.example)) self.assertNotEqual(a, b) b.fromfile(f, len(self.example)) self.assertEqual(a, b) self.assertRaises(EOFError, b.fromfile, f, 1) f.close() finally: if not f.closed: f.close() test_support.unlink(test_support.TESTFN) def test_tofromlist(self): a = array.array(self.typecode, 2*self.example) b = array.array(self.typecode) self.assertRaises(TypeError, a.tolist, 42) self.assertRaises(TypeError, b.fromlist) self.assertRaises(TypeError, b.fromlist, 42) self.assertRaises(TypeError, b.fromlist, [None]) b.fromlist(a.tolist()) self.assertEqual(a, b) def test_tofromstring(self): a = array.array(self.typecode, 2*self.example) b = array.array(self.typecode) self.assertRaises(TypeError, a.tostring, 42) self.assertRaises(TypeError, b.fromstring) self.assertRaises(TypeError, b.fromstring, 42) b.fromstring(a.tostring()) self.assertEqual(a, b) if a.itemsize>1: self.assertRaises(ValueError, b.fromstring, "x") def test_repr(self): a = array.array(self.typecode, 2*self.example) self.assertEqual(a, eval(repr(a), {"array": array.array})) a = array.array(self.typecode) self.assertEqual(repr(a), "array('%s')" % self.typecode) def test_str(self): a = array.array(self.typecode, 2*self.example) str(a) def test_cmp(self): a = array.array(self.typecode, self.example) self.assert_((a == 42) is False) self.assert_((a != 42) is True) self.assert_((a == a) is True) self.assert_((a != a) is False) self.assert_((a < a) is False) self.assert_((a <= a) is True) self.assert_((a > a) is False) self.assert_((a >= a) is True) as = array.array(self.typecode, self.smallerexample) ab = array.array(self.typecode, self.biggerexample) self.assert_((a == 2*a) is False) self.assert_((a != 2*a) is True) self.assert_((a < 2*a) is True) self.assert_((a <= 2*a) is True) self.assert_((a > 2*a) is False) self.assert_((a >= 2*a) is False) self.assert_((a == as) is False) self.assert_((a != as) is True) self.assert_((a < as) is False) self.assert_((a <= as) is False) self.assert_((a > as) is True) self.assert_((a >= as) is True) self.assert_((a == ab) is False) self.assert_((a != ab) is True) self.assert_((a < ab) is True) self.assert_((a <= ab) is True) self.assert_((a > ab) is False) self.assert_((a >= ab) is False) def test_add(self): a = array.array(self.typecode, self.example) \ + array.array(self.typecode, self.example[::-1]) self.assertEqual( a, array.array(self.typecode, self.example + self.example[::-1]) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__add__, b) self.assertRaises(TypeError, a.__add__, "bad") def test_iadd(self): a = array.array(self.typecode, self.example[::-1]) b = a a += array.array(self.typecode, 2*self.example) self.assert_(a is b) self.assertEqual( a, array.array(self.typecode, self.example[::-1]+2*self.example) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__add__, b) self.assertRaises(TypeError, a.__iadd__, "bad") def test_mul(self): a = 5*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode, 5*self.example) ) a = array.array(self.typecode, self.example)*5 self.assertEqual( a, array.array(self.typecode, self.example*5) ) a = 0*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode) ) a = (-1)*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode) ) self.assertRaises(TypeError, a.__mul__, "bad") def test_imul(self): a = array.array(self.typecode, self.example) b = a a *= 5 self.assert_(a is b) self.assertEqual( a, array.array(self.typecode, 5*self.example) ) a *= 0 self.assert_(a is b) self.assertEqual(a, array.array(self.typecode)) a *= 1000 self.assert_(a is b) self.assertEqual(a, array.array(self.typecode)) a *= -1 self.assert_(a is b) self.assertEqual(a, array.array(self.typecode)) a = array.array(self.typecode, self.example) a *= -1 self.assertEqual(a, array.array(self.typecode)) self.assertRaises(TypeError, a.__imul__, "bad") def test_getitem(self): a = array.array(self.typecode, self.example) self.assertEntryEqual(a[0], self.example[0]) self.assertEntryEqual(a[0L], self.example[0]) self.assertEntryEqual(a[-1], self.example[-1]) self.assertEntryEqual(a[-1L], self.example[-1]) self.assertEntryEqual(a[len(self.example)-1], self.example[-1]) self.assertEntryEqual(a[-len(self.example)], self.example[0]) self.assertRaises(TypeError, a.__getitem__) self.assertRaises(IndexError, a.__getitem__, len(self.example)) self.assertRaises(IndexError, a.__getitem__, -len(self.example)-1) def test_setitem(self): a = array.array(self.typecode, self.example) a[0] = a[-1] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[0L] = a[-1] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-1L] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[len(self.example)-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-len(self.example)] = a[-1] self.assertEntryEqual(a[0], a[-1]) self.assertRaises(TypeError, a.__setitem__) self.assertRaises(TypeError, a.__setitem__, None) self.assertRaises(TypeError, a.__setitem__, 0, None) self.assertRaises( IndexError, a.__setitem__, len(self.example), self.example[0] ) self.assertRaises( IndexError, a.__setitem__, -len(self.example)-1, self.example[0] ) def test_delitem(self): a = array.array(self.typecode, self.example) del a[0] self.assertEqual( a, array.array(self.typecode, self.example[1:]) ) a = array.array(self.typecode, self.example) del a[-1] self.assertEqual( a, array.array(self.typecode, self.example[:-1]) ) a = array.array(self.typecode, self.example) del a[len(self.example)-1] self.assertEqual( a, array.array(self.typecode, self.example[:-1]) ) a = array.array(self.typecode, self.example) del a[-len(self.example)] self.assertEqual( a, array.array(self.typecode, self.example[1:]) ) self.assertRaises(TypeError, a.__delitem__) self.assertRaises(TypeError, a.__delitem__, None) self.assertRaises(IndexError, a.__delitem__, len(self.example)) self.assertRaises(IndexError, a.__delitem__, -len(self.example)-1) def test_getslice(self): a = array.array(self.typecode, self.example) self.assertEqual(a[:], a) self.assertEqual( a[1:], array.array(self.typecode, self.example[1:]) ) self.assertEqual( a[:1], array.array(self.typecode, self.example[:1]) ) self.assertEqual( a[:-1], array.array(self.typecode, self.example[:-1]) ) self.assertEqual( a[-1:], array.array(self.typecode, self.example[-1:]) ) self.assertEqual( a[-1:-1], array.array(self.typecode) ) self.assertEqual( a[1000:], array.array(self.typecode) ) self.assertEqual(a[-1000:], a) self.assertEqual(a[:1000], a) self.assertEqual( a[:-1000], array.array(self.typecode) ) self.assertEqual(a[-1000:1000], a) self.assertEqual( a[2000:1000], array.array(self.typecode) ) def test_setslice(self): a = array.array(self.typecode, self.example) a[:1] = a self.assertEqual( a, array.array(self.typecode, self.example + self.example[1:]) ) a = array.array(self.typecode, self.example) a[:-1] = a self.assertEqual( a, array.array(self.typecode, self.example + self.example[-1:]) ) a = array.array(self.typecode, self.example) a[-1:] = a self.assertEqual( a, array.array(self.typecode, self.example[:-1] + self.example) ) a = array.array(self.typecode, self.example) a[1:] = a self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example) ) a = array.array(self.typecode, self.example) a[1:-1] = a self.assertEqual( a, array.array( self.typecode, self.example[:1] + self.example + self.example[-1:] ) ) a = array.array(self.typecode, self.example) a[1000:] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) a[-1000:] = a self.assertEqual( a, array.array(self.typecode, self.example) ) a = array.array(self.typecode, self.example) a[:1000] = a self.assertEqual( a, array.array(self.typecode, self.example) ) a = array.array(self.typecode, self.example) a[:-1000] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) a[1:0] = a self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example + self.example[1:]) ) a = array.array(self.typecode, self.example) a[2000:1000] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.__setslice__, 0, 0, None) self.assertRaises(TypeError, a.__setitem__, slice(0, 1), None) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__setslice__, 0, 0, b) self.assertRaises(TypeError, a.__setitem__, slice(0, 1), b) def test_index(self): example = 2*self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.index) for x in example: self.assertEqual(a.index(x), example.index(x)) self.assertRaises(ValueError, a.index, None) self.assertRaises(ValueError, a.index, self.outside) def test_count(self): example = 2*self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.count) for x in example: self.assertEqual(a.count(x), example.count(x)) self.assertEqual(a.count(self.outside), 0) self.assertEqual(a.count(None), 0) def test_remove(self): for x in self.example: example = 2*self.example a = array.array(self.typecode, example) pos = example.index(x) example2 = example[:pos] + example[pos+1:] a.remove(x) self.assertEqual(a, array.array(self.typecode, example2)) a = array.array(self.typecode, self.example) self.assertRaises(ValueError, a.remove, self.outside) self.assertRaises(ValueError, a.remove, None) def test_pop(self): a = array.array(self.typecode) self.assertRaises(IndexError, a.pop) a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.pop, 42, 42) self.assertRaises(TypeError, a.pop, None) self.assertRaises(IndexError, a.pop, len(a)) self.assertRaises(IndexError, a.pop, -len(a)-1) self.assertEntryEqual(a.pop(0), self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example[1:]+self.example) ) self.assertEntryEqual(a.pop(1), self.example[2]) self.assertEqual( a, array.array(self.typecode, self.example[1:2]+self.example[3:]+self.example) ) self.assertEntryEqual(a.pop(0), self.example[1]) self.assertEntryEqual(a.pop(), self.example[-1]) self.assertEqual( a, array.array(self.typecode, self.example[3:]+self.example[:-1]) ) def test_reverse(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.reverse, 42) a.reverse() self.assertEqual( a, array.array(self.typecode, self.example[::-1]) ) def test_extend(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.extend) a.extend(array.array(self.typecode, self.example[::-1])) self.assertEqual( a, array.array(self.typecode, self.example+self.example[::-1]) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.extend, b) a = array.array(self.typecode, self.example) a.extend(self.example[::-1]) self.assertEqual( a, array.array(self.typecode, self.example+self.example[::-1]) ) def test_constructor_with_iterable_argument(self): a = array.array(self.typecode, iter(self.example)) b = array.array(self.typecode, self.example) self.assertEqual(a, b) # non-iterable argument self.assertRaises(TypeError, array.array, self.typecode, 10) # pass through errors raised in __iter__ class A: def __iter__(self): raise UnicodeError self.assertRaises(UnicodeError, array.array, self.typecode, A()) # pass through errors raised in next() def B(): raise UnicodeError yield None self.assertRaises(UnicodeError, array.array, self.typecode, B()) def test_coveritertraverse(self): try: import gc except ImportError: return a = array.array(self.typecode) l = [iter(a)] l.append(l) gc.collect() def test_buffer(self): a = array.array(self.typecode, self.example) b = buffer(a) self.assertEqual(b[0], a.tostring()[0]) def DONOTtest_weakref(self): # XXX disabled until PyPy grows weakref support s = array.array(self.typecode, self.example) p = proxy(s) self.assertEqual(p.tostring(), s.tostring()) s = None self.assertRaises(ReferenceError, len, p) def test_bug_782369(self): import sys if hasattr(sys, "getrefcount"): for i in range(10): b = array.array('B', range(64)) rc = sys.getrefcount(10) for i in range(10): b = array.array('B', range(64)) self.assertEqual(rc, sys.getrefcount(10)) class StringTest(BaseTest): def test_setitem(self): super(StringTest, self).test_setitem() a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2]) class CharacterTest(StringTest): typecode = 'c' example = '\x01azAZ\x00\xfe' smallerexample = '\x01azAY\x00\xfe' biggerexample = '\x01azAZ\x00\xff' outside = '\x33' minitemsize = 1 def test_subbclassing(self): class EditableString(array.array): def __new__(cls, s, *args, **kwargs): return array.array.__new__(cls, 'c', s) def __init__(self, s, color='blue'): array.array.__init__(self, 'c', s) self.color = color def strip(self): self[:] = array.array('c', self.tostring().strip()) def __repr__(self): return 'EditableString(%r)' % self.tostring() s = EditableString("\ttest\r\n") s.strip() self.assertEqual(s.tostring(), "test") self.assertEqual(s.color, "blue") s.color = "red" self.assertEqual(s.color, "red") self.assertEqual(s.__dict__.keys(), ["color"]) def test_nounicode(self): a = array.array(self.typecode, self.example) self.assertRaises(ValueError, a.fromunicode, unicode('')) self.assertRaises(ValueError, a.tounicode) tests.append(CharacterTest) if test_support.have_unicode: class UnicodeTest(StringTest): typecode = 'u' example = unicode(r'\x01\u263a\x00\ufeff', 'unicode-escape') smallerexample = unicode(r'\x01\u263a\x00\ufefe', 'unicode-escape') biggerexample = unicode(r'\x01\u263a\x01\ufeff', 'unicode-escape') outside = unicode('\x33') minitemsize = 2 def test_unicode(self): self.assertRaises(TypeError, array.array, 'b', unicode('foo', 'ascii')) a = array.array('u', unicode(r'\xa0\xc2\u1234', 'unicode-escape')) a.fromunicode(unicode(' ', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode(r'\x11abc\xff\u1234', 'unicode-escape')) s = a.tounicode() self.assertEqual( s, unicode(r'\xa0\xc2\u1234 \x11abc\xff\u1234', 'unicode-escape') ) s = unicode(r'\x00="\'a\\b\x80\xff\u0000\u0001\u1234', 'unicode-escape') a = array.array('u', s) self.assertEqual( repr(a), r"""array('u', u'\x00="\'a\\b\x80\xff\x00\x01\u1234')""" ) self.assertRaises(TypeError, a.fromunicode) def test_byteswap(self): import sys if sys.maxunicode > 0xffff: return # Byteswapping results in invalid unicode characters for # UCS-4 builds. That this works in CPython is really a # bug. StringTest.test_byteswap(self) tests.append(UnicodeTest) class NumberTest(BaseTest): def test_extslice(self): a = array.array(self.typecode, range(5)) self.assertEqual(a[::], a) self.assertEqual(a[::2], array.array(self.typecode, [0,2,4])) self.assertEqual(a[1::2], array.array(self.typecode, [1,3])) self.assertEqual(a[::-1], array.array(self.typecode, [4,3,2,1,0])) self.assertEqual(a[::-2], array.array(self.typecode, [4,2,0])) self.assertEqual(a[3::-2], array.array(self.typecode, [3,1])) self.assertEqual(a[-100:100:], a) self.assertEqual(a[100:-100:-1], a[::-1]) self.assertEqual(a[-100L:100L:2L], array.array(self.typecode, [0,2,4])) self.assertEqual(a[1000:2000:2], array.array(self.typecode, [])) self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, [])) def test_delslice(self): a = array.array(self.typecode, range(5)) del a[::2] self.assertEqual(a, array.array(self.typecode, [1,3])) a = array.array(self.typecode, range(5)) del a[1::2] self.assertEqual(a, array.array(self.typecode, [0,2,4])) a = array.array(self.typecode, range(5)) del a[1::-2] self.assertEqual(a, array.array(self.typecode, [0,2,3,4])) a = array.array(self.typecode, range(10)) del a[::1000] self.assertEqual(a, array.array(self.typecode, [1,2,3,4,5,6,7,8,9])) def test_assignment(self): a = array.array(self.typecode, range(10)) a[::2] = array.array(self.typecode, [42]*5) self.assertEqual(a, array.array(self.typecode, [42, 1, 42, 3, 42, 5, 42, 7, 42, 9])) a = array.array(self.typecode, range(10)) a[::-4] = array.array(self.typecode, [10]*3) self.assertEqual(a, array.array(self.typecode, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])) a = array.array(self.typecode, range(4)) a[::-1] = a self.assertEqual(a, array.array(self.typecode, [3, 2, 1, 0])) a = array.array(self.typecode, range(10)) b = a[:] c = a[:] ins = array.array(self.typecode, range(2)) a[2:3] = ins b[slice(2,3)] = ins c[2:3:] = ins def test_iterationcontains(self): a = array.array(self.typecode, range(10)) self.assertEqual(list(a), range(10)) b = array.array(self.typecode, [20]) self.assertEqual(a[-1] in a, True) self.assertEqual(b[0] not in a, True) def check_overflow(self, lower, upper): # method to be used by subclasses # should not overflow assigning lower limit a = array.array(self.typecode, [lower]) a[0] = lower # should overflow assigning less than lower limit self.assertRaises(OverflowError, array.array, self.typecode, [lower-1]) self.assertRaises(OverflowError, a.__setitem__, 0, lower-1) # should not overflow assigning upper limit a = array.array(self.typecode, [upper]) a[0] = upper # should overflow assigning more than upper limit self.assertRaises(OverflowError, array.array, self.typecode, [upper+1]) self.assertRaises(OverflowError, a.__setitem__, 0, upper+1) def test_subclassing(self): typecode = self.typecode class ExaggeratingArray(array.array): __slots__ = ['offset'] def __new__(cls, typecode, data, offset): return array.array.__new__(cls, typecode, data) def __init__(self, typecode, data, offset): self.offset = offset def __getitem__(self, i): return array.array.__getitem__(self, i) + self.offset a = ExaggeratingArray(self.typecode, [3, 6, 7, 11], 4) self.assertEntryEqual(a[0], 7) self.assertRaises(AttributeError, setattr, a, "color", "blue") class SignedNumberTest(NumberTest): example = [-1, 0, 1, 42, 0x7f] smallerexample = [-1, 0, 1, 42, 0x7e] biggerexample = [-1, 0, 1, 43, 0x7f] outside = 23 def test_overflow(self): a = array.array(self.typecode) lower = -1 * long(pow(2, a.itemsize * 8 - 1)) upper = long(pow(2, a.itemsize * 8 - 1)) - 1L self.check_overflow(lower, upper) class UnsignedNumberTest(NumberTest): example = [0, 1, 17, 23, 42, 0xff] smallerexample = [0, 1, 17, 23, 42, 0xfe] biggerexample = [0, 1, 17, 23, 43, 0xff] outside = 0xaa def test_overflow(self): a = array.array(self.typecode) lower = 0 upper = long(pow(2, a.itemsize * 8)) - 1L self.check_overflow(lower, upper) class ByteTest(SignedNumberTest): typecode = 'b' minitemsize = 1 tests.append(ByteTest) class UnsignedByteTest(UnsignedNumberTest): typecode = 'B' minitemsize = 1 tests.append(UnsignedByteTest) class ShortTest(SignedNumberTest): typecode = 'h' minitemsize = 2 tests.append(ShortTest) class UnsignedShortTest(UnsignedNumberTest): typecode = 'H' minitemsize = 2 tests.append(UnsignedShortTest) class IntTest(SignedNumberTest): typecode = 'i' minitemsize = 2 tests.append(IntTest) class UnsignedIntTest(UnsignedNumberTest): typecode = 'I' minitemsize = 2 tests.append(UnsignedIntTest) class LongTest(SignedNumberTest): typecode = 'l' minitemsize = 4 tests.append(LongTest) class UnsignedLongTest(UnsignedNumberTest): typecode = 'L' minitemsize = 4 tests.append(UnsignedLongTest) class FPTest(NumberTest): example = [-42.0, 0, 42, 1e5, -1e10] smallerexample = [-42.0, 0, 42, 1e5, -2e10] biggerexample = [-42.0, 0, 42, 1e5, 1e10] outside = 23 def assertEntryEqual(self, entry1, entry2): self.assertAlmostEqual(entry1, entry2) def test_byteswap(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.byteswap, 42) if a.itemsize in (1, 2, 4, 8): b = array.array(self.typecode, self.example) b.byteswap() if a.itemsize==1: self.assertEqual(a, b) else: # On alphas treating the byte swapped bit patters as # floats/doubles results in floating point exceptions # => compare the 8bit string values instead self.assertNotEqual(a.tostring(), b.tostring()) b.byteswap() self.assertEqual(a, b) class FloatTest(FPTest): typecode = 'f' minitemsize = 4 tests.append(FloatTest) class DoubleTest(FPTest): typecode = 'd' minitemsize = 8 tests.append(DoubleTest) def test_main(verbose=None): import sys test_support.run_unittest(*tests) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*tests) gc.collect() counts[i] = sys.gettotalrefcount() print counts if __name__ == "__main__": test_main(verbose=True)
Python
#!/usr/bin/env python import unittest from test import test_support import socket import select import time import thread, threading import Queue import sys, gc from weakref import proxy PORT = 50007 HOST = 'localhost' MSG = 'Michael Gilfix was here\n' class SocketTCPTest(unittest.TestCase): def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serv.bind((HOST, PORT)) self.serv.listen(1) def tearDown(self): self.serv.close() self.serv = None class SocketUDPTest(unittest.TestCase): def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serv.bind((HOST, PORT)) def tearDown(self): self.serv.close() self.serv = None class ThreadableTest: """Threadable Test class The ThreadableTest class makes it easy to create a threaded client/server pair from an existing unit test. To create a new threaded class from an existing unit test, use multiple inheritance: class NewClass (OldClass, ThreadableTest): pass This class defines two new fixture functions with obvious purposes for overriding: clientSetUp () clientTearDown () Any new test functions within the class must then define tests in pairs, where the test name is preceeded with a '_' to indicate the client portion of the test. Ex: def testFoo(self): # Server portion def _testFoo(self): # Client portion Any exceptions raised by the clients during their tests are caught and transferred to the main thread to alert the testing framework. Note, the server setup function cannot call any blocking functions that rely on the client thread during setup, unless serverExplicityReady() is called just before the blocking call (such as in setting up a client/server connection and performing the accept() in setUp(). """ def __init__(self): # Swap the true setup function self.__setUp = self.setUp self.__tearDown = self.tearDown self.setUp = self._setUp self.tearDown = self._tearDown def serverExplicitReady(self): """This method allows the server to explicitly indicate that it wants the client thread to proceed. This is useful if the server is about to execute a blocking routine that is dependent upon the client thread during its setup routine.""" self.server_ready.set() def _setUp(self): self.server_ready = threading.Event() self.client_ready = threading.Event() self.done = threading.Event() self.queue = Queue.Queue(1) # Do some munging to start the client test. methodname = self.id() i = methodname.rfind('.') methodname = methodname[i+1:] test_method = getattr(self, '_' + methodname) self.client_thread = thread.start_new_thread( self.clientRun, (test_method,)) self.__setUp() if not self.server_ready.isSet(): self.server_ready.set() self.client_ready.wait() def _tearDown(self): self.__tearDown() self.done.wait() if not self.queue.empty(): msg = self.queue.get() self.fail(msg) def clientRun(self, test_func): self.server_ready.wait() self.client_ready.set() self.clientSetUp() if not callable(test_func): raise TypeError, "test_func must be a callable function" try: test_func() except Exception, strerror: self.queue.put(strerror) self.clientTearDown() def clientSetUp(self): raise NotImplementedError, "clientSetUp must be implemented." def clientTearDown(self): self.done.set() thread.exit() class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest): def __init__(self, methodName='runTest'): SocketTCPTest.__init__(self, methodName=methodName) ThreadableTest.__init__(self) def clientSetUp(self): self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def clientTearDown(self): self.cli.close() self.cli = None ThreadableTest.clientTearDown(self) class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest): def __init__(self, methodName='runTest'): SocketUDPTest.__init__(self, methodName=methodName) ThreadableTest.__init__(self) def clientSetUp(self): self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) class SocketConnectedTest(ThreadedTCPSocketTest): def __init__(self, methodName='runTest'): ThreadedTCPSocketTest.__init__(self, methodName=methodName) def setUp(self): ThreadedTCPSocketTest.setUp(self) # Indicate explicitly we're ready for the client thread to # proceed and then perform the blocking call to accept self.serverExplicitReady() conn, addr = self.serv.accept() self.cli_conn = conn def tearDown(self): self.cli_conn.close() self.cli_conn = None ThreadedTCPSocketTest.tearDown(self) def clientSetUp(self): ThreadedTCPSocketTest.clientSetUp(self) self.cli.connect((HOST, PORT)) self.serv_conn = self.cli def clientTearDown(self): self.serv_conn.close() self.serv_conn = None ThreadedTCPSocketTest.clientTearDown(self) class SocketPairTest(unittest.TestCase, ThreadableTest): def __init__(self, methodName='runTest'): unittest.TestCase.__init__(self, methodName=methodName) ThreadableTest.__init__(self) def setUp(self): self.serv, self.cli = socket.socketpair() def tearDown(self): self.serv.close() self.serv = None def clientSetUp(self): pass def clientTearDown(self): self.cli.close() self.cli = None ThreadableTest.clientTearDown(self) ####################################################################### ## Begin Tests class GeneralModuleTests(unittest.TestCase): def test_weakref(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) p = proxy(s) self.assertEqual(p.fileno(), s.fileno()) s.close() s = None gc.collect() gc.collect() try: p.fileno() except ReferenceError: pass else: self.fail('Socket proxy still exists') def testSocketError(self): # Testing socket module exceptions def raise_error(*args, **kwargs): raise socket.error def raise_herror(*args, **kwargs): raise socket.herror def raise_gaierror(*args, **kwargs): raise socket.gaierror self.failUnlessRaises(socket.error, raise_error, "Error raising socket exception.") self.failUnlessRaises(socket.error, raise_herror, "Error raising socket exception.") self.failUnlessRaises(socket.error, raise_gaierror, "Error raising socket exception.") def testCrucialConstants(self): # Testing for mission critical constants socket.AF_INET socket.SOCK_STREAM socket.SOCK_DGRAM socket.SOCK_RAW socket.SOCK_RDM socket.SOCK_SEQPACKET socket.SOL_SOCKET socket.SO_REUSEADDR def testHostnameRes(self): # Testing hostname resolution mechanisms hostname = socket.gethostname() try: ip = socket.gethostbyname(hostname) except socket.error: # Probably name lookup wasn't set up right; skip this test return self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") try: hname, aliases, ipaddrs = socket.gethostbyaddr(ip) except socket.error: # Probably a similar problem as above; skip this test return all_host_names = [hostname, hname] + aliases fqhn = socket.getfqdn() if not fqhn in all_host_names: self.fail("Error testing host resolution mechanisms.") def testRefCountGetNameInfo(self): # Testing reference count for getnameinfo import sys if hasattr(sys, "getrefcount"): try: # On some versions, this loses a reference orig = sys.getrefcount(__name__) socket.getnameinfo(__name__,0) except SystemError: if sys.getrefcount(__name__) <> orig: self.fail("socket.getnameinfo loses a reference") def testInterpreterCrash(self): # Making sure getnameinfo doesn't crash the interpreter try: # On some versions, this crashes the interpreter. socket.getnameinfo(('x', 0, 0, 0), 0) except socket.error: pass def testNtoH(self): # This just checks that htons etc. are their own inverse, # when looking at the lower 16 or 32 bits. sizes = {socket.htonl: 32, socket.ntohl: 32, socket.htons: 16, socket.ntohs: 16} for func, size in sizes.items(): mask = (1L<<size) - 1 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): self.assertEqual(i & mask, func(func(i&mask)) & mask) swapped = func(mask) self.assertEqual(swapped & mask, mask) self.assertRaises(OverflowError, func, 1L<<34) def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6', 'darwin'): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf it it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) def testDefaultTimeout(self): # Testing default timeout # The default timeout should initially be None self.assertEqual(socket.getdefaulttimeout(), None) s = socket.socket() self.assertEqual(s.gettimeout(), None) s.close() # Set the default timeout to 10, and see if it propagates socket.setdefaulttimeout(10) self.assertEqual(socket.getdefaulttimeout(), 10) s = socket.socket() self.assertEqual(s.gettimeout(), 10) s.close() # Reset the default timeout to None, and see if it propagates socket.setdefaulttimeout(None) self.assertEqual(socket.getdefaulttimeout(), None) s = socket.socket() self.assertEqual(s.gettimeout(), None) s.close() # Check that setting it to an invalid value raises ValueError self.assertRaises(ValueError, socket.setdefaulttimeout, -1) # Check that setting it to an invalid type raises TypeError self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") def testIPv4toString(self): if not hasattr(socket, 'inet_pton'): return # No inet_pton() on this platform from socket import inet_aton as f, inet_pton, AF_INET g = lambda a: inet_pton(AF_INET, a) self.assertEquals('\x00\x00\x00\x00', f('0.0.0.0')) self.assertEquals('\xff\x00\xff\x00', f('255.0.255.0')) self.assertEquals('\xaa\xaa\xaa\xaa', f('170.170.170.170')) self.assertEquals('\x01\x02\x03\x04', f('1.2.3.4')) self.assertEquals('\x00\x00\x00\x00', g('0.0.0.0')) self.assertEquals('\xff\x00\xff\x00', g('255.0.255.0')) self.assertEquals('\xaa\xaa\xaa\xaa', g('170.170.170.170')) def testIPv6toString(self): if not hasattr(socket, 'inet_pton'): return # No inet_pton() on this platform try: from socket import inet_pton, AF_INET6, has_ipv6 if not has_ipv6: return except ImportError: return f = lambda a: inet_pton(AF_INET6, a) self.assertEquals('\x00' * 16, f('::')) self.assertEquals('\x00' * 16, f('0::0')) self.assertEquals('\x00\x01' + '\x00' * 14, f('1::')) self.assertEquals( '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') ) def testStringToIPv4(self): if not hasattr(socket, 'inet_ntop'): return # No inet_ntop() on this platform from socket import inet_ntoa as f, inet_ntop, AF_INET g = lambda a: inet_ntop(AF_INET, a) self.assertEquals('1.0.1.0', f('\x01\x00\x01\x00')) self.assertEquals('170.85.170.85', f('\xaa\x55\xaa\x55')) self.assertEquals('255.255.255.255', f('\xff\xff\xff\xff')) self.assertEquals('1.2.3.4', f('\x01\x02\x03\x04')) self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00')) self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55')) self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff')) def testStringToIPv6(self): if not hasattr(socket, 'inet_ntop'): return # No inet_ntop() on this platform try: from socket import inet_ntop, AF_INET6, has_ipv6 if not has_ipv6: return except ImportError: return f = lambda a: inet_ntop(AF_INET6, a) self.assertEquals('::', f('\x00' * 16)) self.assertEquals('::1', f('\x00' * 15 + '\x01')) self.assertEquals( 'aef:b01:506:1001:ffff:9997:55:170', f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') ) # XXX The following don't test module-level functionality... def testSockName(self): # Testing getsockname() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("0.0.0.0", PORT+1)) name = sock.getsockname() self.assertEqual(name, ("0.0.0.0", PORT+1)) def testGetSockOpt(self): # Testing getsockopt() # We know a socket should start without reuse==0 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) self.failIf(reuse != 0, "initial mode is reuse") def testSetSockOpt(self): # Testing setsockopt() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) self.failIf(reuse == 0, "failed to set reuse mode") def testSendAfterClose(self): # testing send() after close() with timeout sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) sock.close() self.assertRaises(socket.error, sock.send, "spam") class BasicTCPTest(SocketConnectedTest): def __init__(self, methodName='runTest'): SocketConnectedTest.__init__(self, methodName=methodName) def testRecv(self): # Testing large receive over TCP msg = self.cli_conn.recv(1024) self.assertEqual(msg, MSG) def _testRecv(self): self.serv_conn.send(MSG) def testOverFlowRecv(self): # Testing receive in chunks over TCP seg1 = self.cli_conn.recv(len(MSG) - 3) seg2 = self.cli_conn.recv(1024) msg = seg1 + seg2 self.assertEqual(msg, MSG) def _testOverFlowRecv(self): self.serv_conn.send(MSG) def testRecvFrom(self): # Testing large recvfrom() over TCP msg, addr = self.cli_conn.recvfrom(1024) self.assertEqual(msg, MSG) def _testRecvFrom(self): self.serv_conn.send(MSG) def testOverFlowRecvFrom(self): # Testing recvfrom() in chunks over TCP seg1, addr = self.cli_conn.recvfrom(len(MSG)-3) seg2, addr = self.cli_conn.recvfrom(1024) msg = seg1 + seg2 self.assertEqual(msg, MSG) def _testOverFlowRecvFrom(self): self.serv_conn.send(MSG) def testSendAll(self): # Testing sendall() with a 2048 byte string over TCP msg = '' while 1: read = self.cli_conn.recv(1024) if not read: break msg += read self.assertEqual(msg, 'f' * 2048) def _testSendAll(self): big_chunk = 'f' * 2048 self.serv_conn.sendall(big_chunk) def testFromFd(self): # Testing fromfd() if not hasattr(socket, "fromfd"): return # On Windows, this doesn't exist fd = self.cli_conn.fileno() sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) msg = sock.recv(1024) self.assertEqual(msg, MSG) def _testFromFd(self): self.serv_conn.send(MSG) def testShutdown(self): # Testing shutdown() msg = self.cli_conn.recv(1024) self.assertEqual(msg, MSG) def _testShutdown(self): self.serv_conn.send(MSG) self.serv_conn.shutdown(2) class BasicUDPTest(ThreadedUDPSocketTest): def __init__(self, methodName='runTest'): ThreadedUDPSocketTest.__init__(self, methodName=methodName) def testSendtoAndRecv(self): # Testing sendto() and Recv() over UDP msg = self.serv.recv(len(MSG)) self.assertEqual(msg, MSG) def _testSendtoAndRecv(self): self.cli.sendto(MSG, 0, (HOST, PORT)) def testRecvFrom(self): # Testing recvfrom() over UDP msg, addr = self.serv.recvfrom(len(MSG)) self.assertEqual(msg, MSG) def _testRecvFrom(self): self.cli.sendto(MSG, 0, (HOST, PORT)) class BasicSocketPairTest(SocketPairTest): def __init__(self, methodName='runTest'): SocketPairTest.__init__(self, methodName=methodName) def testRecv(self): msg = self.serv.recv(1024) self.assertEqual(msg, MSG) def _testRecv(self): self.cli.send(MSG) def testSend(self): self.serv.send(MSG) def _testSend(self): msg = self.cli.recv(1024) self.assertEqual(msg, MSG) class NonBlockingTCPTests(ThreadedTCPSocketTest): def __init__(self, methodName='runTest'): ThreadedTCPSocketTest.__init__(self, methodName=methodName) def testSetBlocking(self): # Testing whether set blocking works self.serv.setblocking(0) start = time.time() try: self.serv.accept() except socket.error: pass end = time.time() self.assert_((end - start) < 1.0, "Error setting non-blocking mode.") def _testSetBlocking(self): pass def testAccept(self): # Testing non-blocking accept self.serv.setblocking(0) try: conn, addr = self.serv.accept() except socket.error: pass else: self.fail("Error trying to do non-blocking accept.") read, write, err = select.select([self.serv], [], []) if self.serv in read: conn, addr = self.serv.accept() else: self.fail("Error trying to do accept after select.") def _testAccept(self): time.sleep(0.1) self.cli.connect((HOST, PORT)) def testConnect(self): # Testing non-blocking connect conn, addr = self.serv.accept() def _testConnect(self): self.cli.settimeout(10) self.cli.connect((HOST, PORT)) def testRecv(self): # Testing non-blocking recv conn, addr = self.serv.accept() conn.setblocking(0) try: msg = conn.recv(len(MSG)) except socket.error: pass else: self.fail("Error trying to do non-blocking recv.") read, write, err = select.select([conn], [], []) if conn in read: msg = conn.recv(len(MSG)) self.assertEqual(msg, MSG) else: self.fail("Error during select call to non-blocking socket.") def _testRecv(self): self.cli.connect((HOST, PORT)) time.sleep(0.1) self.cli.send(MSG) class FileObjectClassTestCase(SocketConnectedTest): bufsize = -1 # Use default buffer size def __init__(self, methodName='runTest'): SocketConnectedTest.__init__(self, methodName=methodName) def setUp(self): SocketConnectedTest.setUp(self) self.serv_file = self.cli_conn.makefile('rb', self.bufsize) def tearDown(self): self.serv_file.close() self.assert_(self.serv_file.closed) self.serv_file = None SocketConnectedTest.tearDown(self) def clientSetUp(self): SocketConnectedTest.clientSetUp(self) self.cli_file = self.serv_conn.makefile('wb') def clientTearDown(self): self.cli_file.close() self.assert_(self.cli_file.closed) self.cli_file = None SocketConnectedTest.clientTearDown(self) def testSmallRead(self): # Performing small file read test first_seg = self.serv_file.read(len(MSG)-3) second_seg = self.serv_file.read(3) msg = first_seg + second_seg self.assertEqual(msg, MSG) def _testSmallRead(self): self.cli_file.write(MSG) self.cli_file.flush() def testFullRead(self): # read until EOF msg = self.serv_file.read() self.assertEqual(msg, MSG) def _testFullRead(self): self.cli_file.write(MSG) self.cli_file.close() def testUnbufferedRead(self): # Performing unbuffered file read test buf = '' while 1: char = self.serv_file.read(1) if not char: break buf += char self.assertEqual(buf, MSG) def _testUnbufferedRead(self): self.cli_file.write(MSG) self.cli_file.flush() def testReadline(self): # Performing file readline test line = self.serv_file.readline() self.assertEqual(line, MSG) def _testReadline(self): self.cli_file.write(MSG) self.cli_file.flush() def testClosedAttr(self): self.assert_(not self.serv_file.closed) def _testClosedAttr(self): self.assert_(not self.cli_file.closed) class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase): """Repeat the tests from FileObjectClassTestCase with bufsize==0. In this case (and in this case only), it should be possible to create a file object, read a line from it, create another file object, read another line from it, without loss of data in the first file object's buffer. Note that httplib relies on this when reading multiple requests from the same socket.""" bufsize = 0 # Use unbuffered mode def testUnbufferedReadline(self): # Read a line, create a new file object, read another line with it line = self.serv_file.readline() # first line self.assertEqual(line, "A. " + MSG) # first line self.serv_file = self.cli_conn.makefile('rb', 0) line = self.serv_file.readline() # second line self.assertEqual(line, "B. " + MSG) # second line def _testUnbufferedReadline(self): self.cli_file.write("A. " + MSG) self.cli_file.write("B. " + MSG) self.cli_file.flush() class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase): bufsize = 1 # Default-buffered for reading; line-buffered for writing class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase): bufsize = 2 # Exercise the buffering code class TCPTimeoutTest(SocketTCPTest): def testTCPTimeout(self): def raise_timeout(*args, **kwargs): self.serv.settimeout(1.0) self.serv.accept() self.failUnlessRaises(socket.timeout, raise_timeout, "Error generating a timeout exception (TCP)") def testTimeoutZero(self): ok = False try: self.serv.settimeout(0.0) foo = self.serv.accept() except socket.timeout: self.fail("caught timeout instead of error (TCP)") except socket.error: ok = True except: self.fail("caught unexpected exception (TCP)") if not ok: self.fail("accept() returned success when we did not expect it") class UDPTimeoutTest(SocketTCPTest): def testUDPTimeout(self): def raise_timeout(*args, **kwargs): self.serv.settimeout(1.0) self.serv.recv(1024) self.failUnlessRaises(socket.timeout, raise_timeout, "Error generating a timeout exception (UDP)") def testTimeoutZero(self): ok = False try: self.serv.settimeout(0.0) foo = self.serv.recv(1024) except socket.timeout: self.fail("caught timeout instead of error (UDP)") except socket.error: ok = True except: self.fail("caught unexpected exception (UDP)") if not ok: self.fail("recv() returned success when we did not expect it") class TestExceptions(unittest.TestCase): def testExceptionTree(self): self.assert_(issubclass(socket.error, Exception)) self.assert_(issubclass(socket.herror, socket.error)) self.assert_(issubclass(socket.gaierror, socket.error)) self.assert_(issubclass(socket.timeout, socket.error)) def test_main(): tests = [GeneralModuleTests, BasicTCPTest, TCPTimeoutTest, TestExceptions] if sys.platform != 'mac': tests.extend([ BasicUDPTest, UDPTimeoutTest ]) tests.extend([ NonBlockingTCPTests, FileObjectClassTestCase, UnbufferedFileObjectClassTestCase, LineBufferedFileObjectClassTestCase, SmallBufferedFileObjectClassTestCase ]) if hasattr(socket, "socketpair"): tests.append(BasicSocketPairTest) test_support.run_unittest(*tests) if __name__ == "__main__": test_main()
Python
""" Common tests shared by test_str, test_unicode, test_userstring and test_string. """ import unittest, string, sys, operator from test import test_support from UserList import UserList class Sequence: def __init__(self, seq='wxyz'): self.seq = seq def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[i] class BadSeq1(Sequence): def __init__(self): self.seq = [7, 'hello', 123L] class BadSeq2(Sequence): def __init__(self): self.seq = ['a', 'b', 'c'] def __len__(self): return 8 class CommonTest(unittest.TestCase): # This testcase contains test that can be used in all # stringlike classes. Currently this is str, unicode # UserString and the string module. # The type to be tested # Change in subclasses to change the behaviour of fixtesttype() type2test = None # All tests pass their arguments to the testing methods # as str objects. fixtesttype() can be used to propagate # these arguments to the appropriate type def fixtype(self, obj): if isinstance(obj, str): return self.__class__.type2test(obj) elif isinstance(obj, list): return [self.fixtype(x) for x in obj] elif isinstance(obj, tuple): return tuple([self.fixtype(x) for x in obj]) elif isinstance(obj, dict): return dict([ (self.fixtype(key), self.fixtype(value)) for (key, value) in obj.iteritems() ]) else: return obj # single this out, because UserString cannot cope with fixed args fixargs = fixtype subclasscheck = True # check that object.method(*args) returns result def checkequal(self, result, object, methodname, *args): result = self.fixtype(result) object = self.fixtype(object) args = self.fixargs(args) realresult = getattr(object, methodname)(*args) self.assertEqual( result, realresult ) # if the original is returned make sure that # this doesn't happen with subclasses if object == realresult and self.subclasscheck: class subtype(self.__class__.type2test): pass object = subtype(object) realresult = getattr(object, methodname)(*args) self.assert_(object is not realresult) # check that op(*args) returns result def checkop(self, result, op, *args): result = self.fixtype(result) object = self.fixtype(args[0]) args = self.fixargs(args[1:]) realresult = op(object, *args) self.assertEqual( result, realresult ) # if the original is returned make sure that # this doesn't happen with subclasses if object == realresult and self.subclasscheck: class subtype(self.__class__.type2test): pass object = subtype(object) realresult = op(object, *args) self.assert_(object is not realresult) # check that object.method(*args) raises exc def checkraises(self, exc, object, methodname, *args): object = self.fixtype(object) args = self.fixargs(args) self.assertRaises( exc, getattr(object, methodname), *args ) # check that op(*args) raises exc def checkopraises(self, exc, op, *args): object = self.fixtype(args[0]) args = self.fixargs(args[1:]) self.assertRaises( exc, op, object, *args ) # call object.method(*args) without any checks def checkcall(self, object, methodname, *args): object = self.fixtype(object) args = self.fixargs(args) getattr(object, methodname)(*args) # call op(*args) without any checks def checkopcall(self, op, *args): object = self.fixtype(args[0]) args = self.fixargs(args[1:]) op(object, *args) def test_hash(self): # SF bug 1054139: += optimization was not invalidating cached hash value a = self.type2test('DNSSEC') b = self.type2test('') for c in a: b += c hash(b) self.assertEqual(hash(a), hash(b)) def test_capitalize(self): self.checkequal(' hello ', ' hello ', 'capitalize') self.checkequal('Hello ', 'Hello ','capitalize') self.checkequal('Hello ', 'hello ','capitalize') self.checkequal('Aaaa', 'aaaa', 'capitalize') self.checkequal('Aaaa', 'AaAa', 'capitalize') self.checkraises(TypeError, 'hello', 'capitalize', 42) def test_count(self): self.checkequal(3, 'aaa', 'count', 'a') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(3, 'aaa', 'count', 'a') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(3, 'aaa', 'count', 'a') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(1, 'aaa', 'count', 'a', -1) self.checkequal(3, 'aaa', 'count', 'a', -10) self.checkequal(2, 'aaa', 'count', 'a', 0, -1) self.checkequal(0, 'aaa', 'count', 'a', 0, -10) self.checkraises(TypeError, 'hello', 'count') self.checkraises(TypeError, 'hello', 'count', 42) def test_find(self): self.checkequal(0, 'abcdefghiabc', 'find', 'abc') self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1) self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4) self.checkraises(TypeError, 'hello', 'find') self.checkraises(TypeError, 'hello', 'find', 42) def test_rfind(self): self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc') self.checkequal(12, 'abcdefghiabc', 'rfind', '') self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd') self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz') self.checkraises(TypeError, 'hello', 'rfind') self.checkraises(TypeError, 'hello', 'rfind', 42) def test_index(self): self.checkequal(0, 'abcdefghiabc', 'index', '') self.checkequal(3, 'abcdefghiabc', 'index', 'def') self.checkequal(0, 'abcdefghiabc', 'index', 'abc') self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1) self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib') self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1) self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8) self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1) self.checkraises(TypeError, 'hello', 'index') self.checkraises(TypeError, 'hello', 'index', 42) def test_rindex(self): self.checkequal(12, 'abcdefghiabc', 'rindex', '') self.checkequal(3, 'abcdefghiabc', 'rindex', 'def') self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc') self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1) self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib') self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1) self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1) self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8) self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1) self.checkraises(TypeError, 'hello', 'rindex') self.checkraises(TypeError, 'hello', 'rindex', 42) def test_lower(self): self.checkequal('hello', 'HeLLo', 'lower') self.checkequal('hello', 'hello', 'lower') self.checkraises(TypeError, 'hello', 'lower', 42) def test_upper(self): self.checkequal('HELLO', 'HeLLo', 'upper') self.checkequal('HELLO', 'HELLO', 'upper') self.checkraises(TypeError, 'hello', 'upper', 42) def test_expandtabs(self): self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs') self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8) self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4) self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4) self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs') self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8) self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4) self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42) def test_split(self): self.checkequal(['this', 'is', 'the', 'split', 'function'], 'this is the split function', 'split') # by whitespace self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split') self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1) self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2) self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3) self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4) self.checkequal(['a b c d'], 'a b c d', 'split', None, 0) self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2) # by a char self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|') self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1) self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4) self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0) self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2) self.checkequal(['endcase ', ''], 'endcase |', 'split', '|') self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2) # by string self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//') self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1) self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4) self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0) self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2) self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test') # mixed use of str and unicode self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2) # argument type self.checkraises(TypeError, 'hello', 'split', 42, 42, 42) def test_rsplit(self): self.checkequal(['this', 'is', 'the', 'rsplit', 'function'], 'this is the rsplit function', 'rsplit') # by whitespace self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit') self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1) self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2) self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3) self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4) self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0) self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2) # by a char self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|') self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1) self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4) self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0) self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2) self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|') self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2) # by string self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//') self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1) self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4) self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0) self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2) self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test') # mixed use of str and unicode self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2) # argument type self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42) def test_strip(self): self.checkequal('hello', ' hello ', 'strip') self.checkequal('hello ', ' hello ', 'lstrip') self.checkequal(' hello', ' hello ', 'rstrip') self.checkequal('hello', 'hello', 'strip') # strip/lstrip/rstrip with None arg self.checkequal('hello', ' hello ', 'strip', None) self.checkequal('hello ', ' hello ', 'lstrip', None) self.checkequal(' hello', ' hello ', 'rstrip', None) self.checkequal('hello', 'hello', 'strip', None) # strip/lstrip/rstrip with str arg self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz') self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz') self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz') self.checkequal('hello', 'hello', 'strip', 'xyz') # strip/lstrip/rstrip with unicode arg if test_support.have_unicode: self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy', 'strip', unicode('xyz', 'ascii')) self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy', 'lstrip', unicode('xyz', 'ascii')) self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy', 'rstrip', unicode('xyz', 'ascii')) self.checkequal(unicode('hello', 'ascii'), 'hello', 'strip', unicode('xyz', 'ascii')) self.checkraises(TypeError, 'hello', 'strip', 42, 42) self.checkraises(TypeError, 'hello', 'lstrip', 42, 42) self.checkraises(TypeError, 'hello', 'rstrip', 42, 42) def test_ljust(self): self.checkequal('abc ', 'abc', 'ljust', 10) self.checkequal('abc ', 'abc', 'ljust', 6) self.checkequal('abc', 'abc', 'ljust', 3) self.checkequal('abc', 'abc', 'ljust', 2) self.checkequal('abc*******', 'abc', 'ljust', 10, '*') self.checkraises(TypeError, 'abc', 'ljust') def test_rjust(self): self.checkequal(' abc', 'abc', 'rjust', 10) self.checkequal(' abc', 'abc', 'rjust', 6) self.checkequal('abc', 'abc', 'rjust', 3) self.checkequal('abc', 'abc', 'rjust', 2) self.checkequal('*******abc', 'abc', 'rjust', 10, '*') self.checkraises(TypeError, 'abc', 'rjust') def test_center(self): self.checkequal(' abc ', 'abc', 'center', 10) self.checkequal(' abc ', 'abc', 'center', 6) self.checkequal('abc', 'abc', 'center', 3) self.checkequal('abc', 'abc', 'center', 2) self.checkequal('***abc****', 'abc', 'center', 10, '*') self.checkraises(TypeError, 'abc', 'center') def test_swapcase(self): self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase') self.checkraises(TypeError, 'hello', 'swapcase', 42) def test_replace(self): self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1) self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '') self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2) self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3) self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4) self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0) self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@') self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@') self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2) self.checkequal('-a-b-c-', 'abc', 'replace', '', '-') self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3) self.checkequal('abc', 'abc', 'replace', '', '-', 0) self.checkequal('', '', 'replace', '', '') self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0) self.checkequal('abc', 'abc', 'replace', 'xy', '--') # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with # MemoryError due to empty result (platform malloc issue when requesting # 0 bytes). self.checkequal('', '123', 'replace', '123', '') self.checkequal('', '123123', 'replace', '123', '') self.checkequal('x', '123x123', 'replace', '123', '') self.checkraises(TypeError, 'hello', 'replace') self.checkraises(TypeError, 'hello', 'replace', 42) self.checkraises(TypeError, 'hello', 'replace', 42, 'h') self.checkraises(TypeError, 'hello', 'replace', 'h', 42) def test_zfill(self): self.checkequal('123', '123', 'zfill', 2) self.checkequal('123', '123', 'zfill', 3) self.checkequal('0123', '123', 'zfill', 4) self.checkequal('+123', '+123', 'zfill', 3) self.checkequal('+123', '+123', 'zfill', 4) self.checkequal('+0123', '+123', 'zfill', 5) self.checkequal('-123', '-123', 'zfill', 3) self.checkequal('-123', '-123', 'zfill', 4) self.checkequal('-0123', '-123', 'zfill', 5) self.checkequal('000', '', 'zfill', 3) self.checkequal('34', '34', 'zfill', 1) self.checkequal('0034', '34', 'zfill', 4) self.checkraises(TypeError, '123', 'zfill') class MixinStrUnicodeUserStringTest: # additional tests that only work for # stringlike objects, i.e. str, unicode, UserString # (but not the string module) def test_islower(self): self.checkequal(False, '', 'islower') self.checkequal(True, 'a', 'islower') self.checkequal(False, 'A', 'islower') self.checkequal(False, '\n', 'islower') self.checkequal(True, 'abc', 'islower') self.checkequal(False, 'aBc', 'islower') self.checkequal(True, 'abc\n', 'islower') self.checkraises(TypeError, 'abc', 'islower', 42) def test_isupper(self): self.checkequal(False, '', 'isupper') self.checkequal(False, 'a', 'isupper') self.checkequal(True, 'A', 'isupper') self.checkequal(False, '\n', 'isupper') self.checkequal(True, 'ABC', 'isupper') self.checkequal(False, 'AbC', 'isupper') self.checkequal(True, 'ABC\n', 'isupper') self.checkraises(TypeError, 'abc', 'isupper', 42) def test_istitle(self): self.checkequal(False, '', 'istitle') self.checkequal(False, 'a', 'istitle') self.checkequal(True, 'A', 'istitle') self.checkequal(False, '\n', 'istitle') self.checkequal(True, 'A Titlecased Line', 'istitle') self.checkequal(True, 'A\nTitlecased Line', 'istitle') self.checkequal(True, 'A Titlecased, Line', 'istitle') self.checkequal(False, 'Not a capitalized String', 'istitle') self.checkequal(False, 'Not\ta Titlecase String', 'istitle') self.checkequal(False, 'Not--a Titlecase String', 'istitle') self.checkequal(False, 'NOT', 'istitle') self.checkraises(TypeError, 'abc', 'istitle', 42) def test_isspace(self): self.checkequal(False, '', 'isspace') self.checkequal(False, 'a', 'isspace') self.checkequal(True, ' ', 'isspace') self.checkequal(True, '\t', 'isspace') self.checkequal(True, '\r', 'isspace') self.checkequal(True, '\n', 'isspace') self.checkequal(True, ' \t\r\n', 'isspace') self.checkequal(False, ' \t\r\na', 'isspace') self.checkraises(TypeError, 'abc', 'isspace', 42) def test_isalpha(self): self.checkequal(False, '', 'isalpha') self.checkequal(True, 'a', 'isalpha') self.checkequal(True, 'A', 'isalpha') self.checkequal(False, '\n', 'isalpha') self.checkequal(True, 'abc', 'isalpha') self.checkequal(False, 'aBc123', 'isalpha') self.checkequal(False, 'abc\n', 'isalpha') self.checkraises(TypeError, 'abc', 'isalpha', 42) def test_isalnum(self): self.checkequal(False, '', 'isalnum') self.checkequal(True, 'a', 'isalnum') self.checkequal(True, 'A', 'isalnum') self.checkequal(False, '\n', 'isalnum') self.checkequal(True, '123abc456', 'isalnum') self.checkequal(True, 'a1b3c', 'isalnum') self.checkequal(False, 'aBc000 ', 'isalnum') self.checkequal(False, 'abc\n', 'isalnum') self.checkraises(TypeError, 'abc', 'isalnum', 42) def test_isdigit(self): self.checkequal(False, '', 'isdigit') self.checkequal(False, 'a', 'isdigit') self.checkequal(True, '0', 'isdigit') self.checkequal(True, '0123456789', 'isdigit') self.checkequal(False, '0123456789a', 'isdigit') self.checkraises(TypeError, 'abc', 'isdigit', 42) def test_title(self): self.checkequal(' Hello ', ' hello ', 'title') self.checkequal('Hello ', 'hello ', 'title') self.checkequal('Hello ', 'Hello ', 'title') self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title') self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', ) self.checkequal('Getint', "getInt", 'title') self.checkraises(TypeError, 'hello', 'title', 42) def test_splitlines(self): self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines') self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines') self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines') self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines') self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines') self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines') self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1) self.checkraises(TypeError, 'abc', 'splitlines', 42, 42) def test_startswith(self): self.checkequal(True, 'hello', 'startswith', 'he') self.checkequal(True, 'hello', 'startswith', 'hello') self.checkequal(False, 'hello', 'startswith', 'hello world') self.checkequal(True, 'hello', 'startswith', '') self.checkequal(False, 'hello', 'startswith', 'ello') self.checkequal(True, 'hello', 'startswith', 'ello', 1) self.checkequal(True, 'hello', 'startswith', 'o', 4) self.checkequal(False, 'hello', 'startswith', 'o', 5) self.checkequal(True, 'hello', 'startswith', '', 5) self.checkequal(False, 'hello', 'startswith', 'lo', 6) self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3) self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7) self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6) # test negative indices self.checkequal(True, 'hello', 'startswith', 'he', 0, -1) self.checkequal(True, 'hello', 'startswith', 'he', -53, -1) self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1) self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10) self.checkequal(False, 'hello', 'startswith', 'ello', -5) self.checkequal(True, 'hello', 'startswith', 'ello', -4) self.checkequal(False, 'hello', 'startswith', 'o', -2) self.checkequal(True, 'hello', 'startswith', 'o', -1) self.checkequal(True, 'hello', 'startswith', '', -3, -3) self.checkequal(False, 'hello', 'startswith', 'lo', -9) self.checkraises(TypeError, 'hello', 'startswith') self.checkraises(TypeError, 'hello', 'startswith', 42) def test_endswith(self): self.checkequal(True, 'hello', 'endswith', 'lo') self.checkequal(False, 'hello', 'endswith', 'he') self.checkequal(True, 'hello', 'endswith', '') self.checkequal(False, 'hello', 'endswith', 'hello world') self.checkequal(False, 'helloworld', 'endswith', 'worl') self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9) self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12) self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7) self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7) self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7) self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7) self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8) self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1) self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0) # test negative indices self.checkequal(True, 'hello', 'endswith', 'lo', -2) self.checkequal(False, 'hello', 'endswith', 'he', -2) self.checkequal(True, 'hello', 'endswith', '', -3, -3) self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2) self.checkequal(False, 'helloworld', 'endswith', 'worl', -6) self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1) self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9) self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12) self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3) self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3) self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3) self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4) self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2) self.checkraises(TypeError, 'hello', 'endswith') self.checkraises(TypeError, 'hello', 'endswith', 42) def test___contains__(self): self.checkop(True, operator.contains, '', '') # vereq('' in '', True) self.checkop(True, operator.contains, 'abc', '') # vereq('' in 'abc', True) self.checkop(False, operator.contains, 'abc', '\0') # vereq('\0' in 'abc', False) self.checkop(True, operator.contains, '\0abc', '\0') # vereq('\0' in '\0abc', True) self.checkop(True, operator.contains, 'abc\0', '\0') # vereq('\0' in 'abc\0', True) self.checkop(True, operator.contains, '\0abc', 'a') # vereq('a' in '\0abc', True) self.checkop(True, operator.contains, 'asdf', 'asdf') # vereq('asdf' in 'asdf', True) self.checkop(False, operator.contains, 'asd', 'asdf') # vereq('asdf' in 'asd', False) self.checkop(False, operator.contains, '', 'asdf') # vereq('asdf' in '', False) def test_subscript(self): self.checkop(u'a', operator.getitem, 'abc', 0) self.checkop(u'c', operator.getitem, 'abc', -1) self.checkop(u'a', operator.getitem, 'abc', 0L) self.checkop(u'abc', operator.getitem, 'abc', slice(0, 3)) self.checkop(u'abc', operator.getitem, 'abc', slice(0, 1000)) self.checkop(u'a', operator.getitem, 'abc', slice(0, 1)) self.checkop(u'', operator.getitem, 'abc', slice(0, 0)) # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice) self.checkopraises(TypeError, operator.getitem, 'abc', 'def') def test_slice(self): self.checkop('abc', operator.getslice, 'abc', 0, 1000) self.checkop('abc', operator.getslice, 'abc', 0, 3) self.checkop('ab', operator.getslice, 'abc', 0, 2) self.checkop('bc', operator.getslice, 'abc', 1, 3) self.checkop('b', operator.getslice, 'abc', 1, 2) self.checkop('', operator.getslice, 'abc', 2, 2) self.checkop('', operator.getslice, 'abc', 1000, 1000) self.checkop('', operator.getslice, 'abc', 2000, 1000) self.checkop('', operator.getslice, 'abc', 2, 1) # FIXME What about negative indizes? This is handled differently by [] and __getslice__ self.checkopraises(TypeError, operator.getslice, 'abc', 'def') def test_mul(self): self.checkop('', operator.mul, 'abc', -1) self.checkop('', operator.mul, 'abc', 0) self.checkop('abc', operator.mul, 'abc', 1) self.checkop('abcabcabc', operator.mul, 'abc', 3) self.checkopraises(TypeError, operator.mul, 'abc') self.checkopraises(TypeError, operator.mul, 'abc', '') self.checkopraises(OverflowError, operator.mul, 10000*'abc', 2000000000) def test_join(self): # join now works with any sequence type # moved here, because the argument order is # different in string.join (see the test in # test.test_string.StringTest.test_join) self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd')) self.checkequal('w x y z', ' ', 'join', Sequence()) self.checkequal('abc', 'a', 'join', ('abc',)) self.checkequal('z', 'a', 'join', UserList(['z'])) if test_support.have_unicode: self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c']) self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c']) self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c']) self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')]) self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3]) for i in [5, 25, 125]: self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ['a' * i] * i) self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ('a' * i,) * i) self.checkraises(TypeError, ' ', 'join', BadSeq1()) self.checkequal('a b c', ' ', 'join', BadSeq2()) self.checkraises(TypeError, ' ', 'join') self.checkraises(TypeError, ' ', 'join', 7) self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L])) def test_formatting(self): self.checkop('+hello+', operator.mod, '+%s+', 'hello') self.checkop('+10+', operator.mod, '+%d+', 10) self.checkop('a', operator.mod, "%c", "a") self.checkop('a', operator.mod, "%c", "a") self.checkop('"', operator.mod, "%c", 34) self.checkop('$', operator.mod, "%c", 36) self.checkop('10', operator.mod, "%d", 10) self.checkop('\x7f', operator.mod, "%c", 0x7f) for ordinal in (-100, 0x200000): # unicode raises ValueError, str raises OverflowError self.checkopraises((ValueError, OverflowError), operator.mod, '%c', ordinal) self.checkop(' 42', operator.mod, '%3ld', 42) self.checkop('0042.00', operator.mod, '%07.2f', 42) self.checkop('0042.00', operator.mod, '%07.2F', 42) self.checkopraises(TypeError, operator.mod, 'abc') self.checkopraises(TypeError, operator.mod, '%(foo)s', 42) self.checkopraises(TypeError, operator.mod, '%s%s', (42,)) self.checkopraises(TypeError, operator.mod, '%c', (None,)) self.checkopraises(ValueError, operator.mod, '%(foo', {}) self.checkopraises(TypeError, operator.mod, '%(foo)s %(bar)s', ('foo', 42)) # argument names with properly nested brackets are supported self.checkop('bar', operator.mod, '%((foo))s', {'(foo)': 'bar'}) # 100 is a magic number in PyUnicode_Format, this forces a resize self.checkop(103*'a'+'x', operator.mod, '%sx', 103*'a') self.checkopraises(TypeError, operator.mod, '%*s', ('foo', 'bar')) self.checkopraises(TypeError, operator.mod, '%10.*f', ('foo', 42.)) self.checkopraises(ValueError, operator.mod, '%10', (42,)) def test_floatformatting(self): # float formatting # XXX changed for PyPy to be faster for prec, value in [(0, 3.141592655), (1, 0.01), (2, 120394), (5, 23.01958), (20, 141414.51321098), (49, 0.01), (50, 1e50), (99, 123)]: format = '%%.%if' % prec try: self.checkopcall(operator.mod, format, value) except OverflowError: self.failUnless(abs(value) < 1e25 and prec >= 67, "OverflowError on small examples") class MixinStrStringUserStringTest: # Additional tests for 8bit strings, i.e. str, UserString and # the string module def test_maketrans(self): self.assertEqual( ''.join(map(chr, xrange(256))).replace('abc', 'xyz'), string.maketrans('abc', 'xyz') ) self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw') def test_translate(self): table = string.maketrans('abc', 'xyz') self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def') table = string.maketrans('a', 'A') self.checkequal('Abc', 'abc', 'translate', table) self.checkequal('xyz', 'xyz', 'translate', table) self.checkequal('yz', 'xyz', 'translate', table, 'x') self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip') self.checkraises(ValueError, 'xyz', 'translate', 'too short') class MixinStrUserStringTest: # Additional tests that only work with # 8bit compatible object, i.e. str and UserString def test_encoding_decoding(self): codecs = [('rot13', 'uryyb jbeyq'), ('base64', 'aGVsbG8gd29ybGQ=\n'), ('hex', '68656c6c6f20776f726c64'), ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')] for encoding, data in codecs: self.checkequal(data, 'hello world', 'encode', encoding) self.checkequal('hello world', data, 'decode', encoding) # zlib is optional, so we make the test optional too... try: import zlib except ImportError: pass else: data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' self.checkequal(data, 'hello world', 'encode', 'zlib') self.checkequal('hello world', data, 'decode', 'zlib') self.checkraises(TypeError, 'xyz', 'decode', 42) self.checkraises(TypeError, 'xyz', 'encode', 42) class MixinStrUnicodeTest: # Additional tests that only work with str and unicode. def test_bug1001011(self): # Make sure join returns a NEW object for single item sequences # involving a subclass. # Make sure that it is of the appropriate type. # Check the optimisation still occurs for standard objects. t = self.type2test class subclass(t): pass s1 = subclass("abcd") s2 = t().join([s1]) self.assert_(s1 is not s2) self.assert_(type(s2) is t) # XXX impl. specific optimisation #s1 = t("abcd") #s2 = t().join([s1]) #self.assert_(s1 is s2) # Should also test mixed-type join. if t is unicode: s1 = subclass("abcd") s2 = "".join([s1]) self.assert_(s1 is not s2) self.assert_(type(s2) is t) # XXX impl. specific opt. #s1 = t("abcd") #s2 = "".join([s1]) #self.assert_(s1 is s2) elif t is str: s1 = subclass("abcd") s2 = u"".join([s1]) self.assert_(s1 is not s2) self.assert_(type(s2) is unicode) # promotes! s1 = t("abcd") s2 = u"".join([s1]) self.assert_(s1 is not s2) self.assert_(type(s2) is unicode) # promotes! else: self.fail("unexpected type for MixinStrUnicodeTest %r" % t)
Python
""" Tests common to tuple, list and UserList.UserList """ import unittest from test import test_support class CommonTest(unittest.TestCase): # The type to be tested type2test = None def test_constructors(self): l0 = [] l1 = [0] l2 = [0, 1] u = self.type2test() u0 = self.type2test(l0) u1 = self.type2test(l1) u2 = self.type2test(l2) uu = self.type2test(u) uu0 = self.type2test(u0) uu1 = self.type2test(u1) uu2 = self.type2test(u2) v = self.type2test(tuple(u)) class OtherSeq: def __init__(self, initseq): self.__data = initseq def __len__(self): return len(self.__data) def __getitem__(self, i): return self.__data[i] s = OtherSeq(u0) v0 = self.type2test(s) self.assertEqual(len(v0), len(s)) s = "this is also a sequence" vv = self.type2test(s) self.assertEqual(len(vv), len(s)) def test_truth(self): self.assert_(not self.type2test()) self.assert_(self.type2test([42])) def test_getitem(self): u = self.type2test([0, 1, 2, 3, 4]) for i in xrange(len(u)): self.assertEqual(u[i], i) self.assertEqual(u[long(i)], i) for i in xrange(-len(u), -1): self.assertEqual(u[i], len(u)+i) self.assertEqual(u[long(i)], len(u)+i) self.assertRaises(IndexError, u.__getitem__, -len(u)-1) self.assertRaises(IndexError, u.__getitem__, len(u)) self.assertRaises(ValueError, u.__getitem__, slice(0,10,0)) u = self.type2test() self.assertRaises(IndexError, u.__getitem__, 0) self.assertRaises(IndexError, u.__getitem__, -1) self.assertRaises(TypeError, u.__getitem__) a = self.type2test([10, 11]) self.assertEqual(a[0], 10) self.assertEqual(a[1], 11) self.assertEqual(a[-2], 10) self.assertEqual(a[-1], 11) self.assertRaises(IndexError, a.__getitem__, -3) self.assertRaises(IndexError, a.__getitem__, 3) def test_getslice(self): l = [0, 1, 2, 3, 4] u = self.type2test(l) self.assertEqual(u[0:0], self.type2test()) self.assertEqual(u[1:2], self.type2test([1])) self.assertEqual(u[-2:-1], self.type2test([3])) self.assertEqual(u[-1000:1000], u) self.assertEqual(u[1000:-1000], self.type2test([])) self.assertEqual(u[:], u) self.assertEqual(u[1:None], self.type2test([1, 2, 3, 4])) self.assertEqual(u[None:3], self.type2test([0, 1, 2])) # Extended slices self.assertEqual(u[::], u) self.assertEqual(u[::2], self.type2test([0, 2, 4])) self.assertEqual(u[1::2], self.type2test([1, 3])) self.assertEqual(u[::-1], self.type2test([4, 3, 2, 1, 0])) self.assertEqual(u[::-2], self.type2test([4, 2, 0])) self.assertEqual(u[3::-2], self.type2test([3, 1])) self.assertEqual(u[3:3:-2], self.type2test([])) self.assertEqual(u[3:2:-2], self.type2test([3])) self.assertEqual(u[3:1:-2], self.type2test([3])) self.assertEqual(u[3:0:-2], self.type2test([3, 1])) self.assertEqual(u[::-100], self.type2test([4])) self.assertEqual(u[100:-100:], self.type2test([])) self.assertEqual(u[-100:100:], u) self.assertEqual(u[100:-100:-1], u[::-1]) self.assertEqual(u[-100:100:-1], self.type2test([])) self.assertEqual(u[-100L:100L:2L], self.type2test([0, 2, 4])) # Test extreme cases with long ints a = self.type2test([0,1,2,3,4]) self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2])) self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4])) if hasattr(u, '__getslice__'): self.assertRaises(TypeError, u.__getslice__) def test_contains(self): u = self.type2test([0, 1, 2]) for i in u: self.assert_(i in u) for i in min(u)-1, max(u)+1: self.assert_(i not in u) self.assertRaises(TypeError, u.__contains__) def test_len(self): self.assertEqual(len(self.type2test()), 0) self.assertEqual(len(self.type2test([])), 0) self.assertEqual(len(self.type2test([0])), 1) self.assertEqual(len(self.type2test([0, 1, 2])), 3) def test_minmax(self): u = self.type2test([0, 1, 2]) self.assertEqual(min(u), 0) self.assertEqual(max(u), 2) def test_addmul(self): u1 = self.type2test([0]) u2 = self.type2test([0, 1]) self.assertEqual(u1, u1 + self.type2test()) self.assertEqual(u1, self.type2test() + u1) self.assertEqual(u1 + self.type2test([1]), u2) self.assertEqual(self.type2test([-1]) + u1, self.type2test([-1, 0])) self.assertEqual(self.type2test(), u2*0) self.assertEqual(self.type2test(), 0*u2) self.assertEqual(self.type2test(), u2*0L) self.assertEqual(self.type2test(), 0L*u2) self.assertEqual(u2, u2*1) self.assertEqual(u2, 1*u2) self.assertEqual(u2, u2*1L) self.assertEqual(u2, 1L*u2) self.assertEqual(u2+u2, u2*2) self.assertEqual(u2+u2, 2*u2) self.assertEqual(u2+u2, u2*2L) self.assertEqual(u2+u2, 2L*u2) self.assertEqual(u2+u2+u2, u2*3) self.assertEqual(u2+u2+u2, 3*u2) class subclass(self.type2test): pass u3 = subclass([0, 1]) self.assertEqual(u3, u3*1) self.assert_(u3 is not u3*1) def test_iadd(self): u = self.type2test([0, 1]) u += self.type2test() self.assertEqual(u, self.type2test([0, 1])) u += self.type2test([2, 3]) self.assertEqual(u, self.type2test([0, 1, 2, 3])) u += self.type2test([4, 5]) self.assertEqual(u, self.type2test([0, 1, 2, 3, 4, 5])) u = self.type2test("spam") u += self.type2test("eggs") self.assertEqual(u, self.type2test("spameggs")) def test_imul(self): u = self.type2test([0, 1]) u *= 3 self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1])) #def test_getitemoverwriteiter(self): # # Verify that __getitem__ overrides are not recognized by __iter__ # XXX PyPy behaves differently on this detail # class T(self.type2test): # def __getitem__(self, key): # return str(key) + '!!!' # self.assertEqual(iter(T((1,2))).next(), 1) def test_repeat(self): for m in xrange(4): s = tuple(range(m)) for n in xrange(-3, 5): self.assertEqual(self.type2test(s*n), self.type2test(s)*n) self.assertEqual(self.type2test(s)*(-4), self.type2test([])) #self.assertEqual(id(s), id(s*1)) def test_subscript(self): a = self.type2test([10, 11]) self.assertEqual(a.__getitem__(0L), 10) self.assertEqual(a.__getitem__(1L), 11) self.assertEqual(a.__getitem__(-2L), 10) self.assertEqual(a.__getitem__(-1L), 11) self.assertRaises(IndexError, a.__getitem__, -3) self.assertRaises(IndexError, a.__getitem__, 3) self.assertEqual(a.__getitem__(slice(0,1)), self.type2test([10])) self.assertEqual(a.__getitem__(slice(1,2)), self.type2test([11])) self.assertEqual(a.__getitem__(slice(0,2)), self.type2test([10, 11])) self.assertEqual(a.__getitem__(slice(0,3)), self.type2test([10, 11])) self.assertEqual(a.__getitem__(slice(3,5)), self.type2test([])) self.assertRaises(ValueError, a.__getitem__, slice(0, 10, 0)) self.assertRaises(TypeError, a.__getitem__, 'x')
Python
# Helper script for test_tempfile.py. argv[2] is the number of a file # descriptor which should _not_ be open. Check this by attempting to # write to it -- if we succeed, something is wrong. import sys import os verbose = (sys.argv[1] == 'v') try: fd = int(sys.argv[2]) try: os.write(fd, "blat") except os.error: # Success -- could not write to fd. sys.exit(0) else: if verbose: sys.stderr.write("fd %d is open in child" % fd) sys.exit(1) except StandardError: if verbose: raise sys.exit(1)
Python
# tests common to dict and UserDict import unittest import UserDict class BasicTestMappingProtocol(unittest.TestCase): # This base class can be used to check that an object conforms to the # mapping protocol # Functions that can be useful to override to adapt to dictionary # semantics type2test = None # which class is being tested (overwrite in subclasses) def _reference(self): """Return a dictionary of values which are invariant by storage in the object under test.""" return {1:2, "key1":"value1", "key2":(1,2,3)} def _empty_mapping(self): """Return an empty mapping object""" return self.type2test() def _full_mapping(self, data): """Return a mapping object with the value contained in data dictionary""" x = self._empty_mapping() for key, value in data.items(): x[key] = value return x def __init__(self, *args, **kw): unittest.TestCase.__init__(self, *args, **kw) self.reference = self._reference().copy() # A (key, value) pair not in the mapping key, value = self.reference.popitem() self.other = {key:value} # A (key, value) pair in the mapping key, value = self.reference.popitem() self.inmapping = {key:value} self.reference[key] = value def test_read(self): # Test for read only operations on mapping p = self._empty_mapping() p1 = dict(p) #workaround for singleton objects d = self._full_mapping(self.reference) if d is p: p = p1 #Indexing for key, value in self.reference.items(): self.assertEqual(d[key], value) knownkey = self.other.keys()[0] self.failUnlessRaises(KeyError, lambda:d[knownkey]) #len self.assertEqual(len(p), 0) self.assertEqual(len(d), len(self.reference)) #has_key for k in self.reference: self.assert_(d.has_key(k)) self.assert_(k in d) for k in self.other: self.failIf(d.has_key(k)) self.failIf(k in d) #cmp self.assertEqual(cmp(p,p), 0) self.assertEqual(cmp(d,d), 0) self.assertEqual(cmp(p,d), -1) self.assertEqual(cmp(d,p), 1) #__non__zero__ if p: self.fail("Empty mapping must compare to False") if not d: self.fail("Full mapping must compare to True") # keys(), items(), iterkeys() ... def check_iterandlist(iter, lst, ref): self.assert_(hasattr(iter, 'next')) self.assert_(hasattr(iter, '__iter__')) x = list(iter) self.assert_(set(x)==set(lst)==set(ref)) check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys()) check_iterandlist(iter(d), d.keys(), self.reference.keys()) check_iterandlist(d.itervalues(), d.values(), self.reference.values()) check_iterandlist(d.iteritems(), d.items(), self.reference.items()) #get key, value = d.iteritems().next() knownkey, knownvalue = self.other.iteritems().next() self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.failIf(knownkey in d) def test_write(self): # Test for write operations on mapping p = self._empty_mapping() #Indexing for key, value in self.reference.items(): p[key] = value self.assertEqual(p[key], value) for key in self.reference.keys(): del p[key] self.failUnlessRaises(KeyError, lambda:p[key]) p = self._empty_mapping() #update p.update(self.reference) self.assertEqual(dict(p), self.reference) items = p.items() p = self._empty_mapping() p.update(items) self.assertEqual(dict(p), self.reference) d = self._full_mapping(self.reference) #setdefault key, value = d.iteritems().next() knownkey, knownvalue = self.other.iteritems().next() self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d[key], value) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) self.assertEqual(d[knownkey], knownvalue) #pop self.assertEqual(d.pop(knownkey), knownvalue) self.failIf(knownkey in d) self.assertRaises(KeyError, d.pop, knownkey) default = 909 d[knownkey] = knownvalue self.assertEqual(d.pop(knownkey, default), knownvalue) self.failIf(knownkey in d) self.assertEqual(d.pop(knownkey, default), default) #popitem key, value = d.popitem() self.failIf(key in d) self.assertEqual(value, self.reference[key]) p=self._empty_mapping() self.assertRaises(KeyError, p.popitem) def test_constructor(self): self.assertEqual(self._empty_mapping(), self._empty_mapping()) def test_bool(self): self.assert_(not self._empty_mapping()) self.assert_(self.reference) self.assert_(bool(self._empty_mapping()) is False) self.assert_(bool(self.reference) is True) def test_keys(self): d = self._empty_mapping() self.assertEqual(d.keys(), []) d = self.reference self.assert_(self.inmapping.keys()[0] in d.keys()) self.assert_(self.other.keys()[0] not in d.keys()) self.assertRaises(TypeError, d.keys, None) def test_values(self): d = self._empty_mapping() self.assertEqual(d.values(), []) self.assertRaises(TypeError, d.values, None) def test_items(self): d = self._empty_mapping() self.assertEqual(d.items(), []) self.assertRaises(TypeError, d.items, None) def test_len(self): d = self._empty_mapping() self.assertEqual(len(d), 0) def test_getitem(self): d = self.reference self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0]) self.assertRaises(TypeError, d.__getitem__) def test_update(self): # mapping argument d = self._empty_mapping() d.update(self.other) self.assertEqual(d.items(), self.other.items()) # No argument d = self._empty_mapping() d.update() self.assertEqual(d, self._empty_mapping()) # item sequence d = self._empty_mapping() d.update(self.other.items()) self.assertEqual(d.items(), self.other.items()) # Iterator d = self._empty_mapping() d.update(self.other.iteritems()) self.assertEqual(d.items(), self.other.items()) # FIXME: Doesn't work with UserDict # self.assertRaises((TypeError, AttributeError), d.update, None) self.assertRaises((TypeError, AttributeError), d.update, 42) outerself = self class SimpleUserDict: def __init__(self): self.d = outerself.reference def keys(self): return self.d.keys() def __getitem__(self, i): return self.d[i] d.clear() d.update(SimpleUserDict()) i1 = d.items() i2 = self.reference.items() i1.sort() i2.sort() self.assertEqual(i1, i2) class Exc(Exception): pass d = self._empty_mapping() class FailingUserDict: def keys(self): raise Exc self.assertRaises(Exc, d.update, FailingUserDict()) d.clear() class FailingUserDict: def keys(self): class BogonIter: def __init__(self): self.i = 1 def __iter__(self): return self def next(self): if self.i: self.i = 0 return 'a' raise Exc return BogonIter() def __getitem__(self, key): return key self.assertRaises(Exc, d.update, FailingUserDict()) class FailingUserDict: def keys(self): class BogonIter: def __init__(self): self.i = ord('a') def __iter__(self): return self def next(self): if self.i <= ord('z'): rtn = chr(self.i) self.i += 1 return rtn raise StopIteration return BogonIter() def __getitem__(self, key): raise Exc self.assertRaises(Exc, d.update, FailingUserDict()) d = self._empty_mapping() class badseq(object): def __iter__(self): return self def next(self): raise Exc() self.assertRaises(Exc, d.update, badseq()) self.assertRaises(ValueError, d.update, [(1, 2, 3)]) # no test_fromkeys or test_copy as both os.environ and selves don't support it def test_get(self): d = self._empty_mapping() self.assert_(d.get(self.other.keys()[0]) is None) self.assertEqual(d.get(self.other.keys()[0], 3), 3) d = self.reference self.assert_(d.get(self.other.keys()[0]) is None) self.assertEqual(d.get(self.other.keys()[0], 3), 3) self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0]) self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0]) self.assertRaises(TypeError, d.get) self.assertRaises(TypeError, d.get, None, None, None) def test_setdefault(self): d = self._empty_mapping() self.assertRaises(TypeError, d.setdefault) def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) self.assertRaises(TypeError, d.popitem, 42) def test_pop(self): d = self._empty_mapping() k, v = self.inmapping.items()[0] d[k] = v self.assertRaises(KeyError, d.pop, self.other.keys()[0]) self.assertEqual(d.pop(k), v) self.assertEqual(len(d), 0) self.assertRaises(KeyError, d.pop, k) class TestMappingProtocol(BasicTestMappingProtocol): def test_constructor(self): BasicTestMappingProtocol.test_constructor(self) self.assert_(self._empty_mapping() is not self._empty_mapping()) self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2}) def test_bool(self): BasicTestMappingProtocol.test_bool(self) self.assert_(not self._empty_mapping()) self.assert_(self._full_mapping({"x": "y"})) self.assert_(bool(self._empty_mapping()) is False) self.assert_(bool(self._full_mapping({"x": "y"})) is True) def test_keys(self): BasicTestMappingProtocol.test_keys(self) d = self._empty_mapping() self.assertEqual(d.keys(), []) d = self._full_mapping({'a': 1, 'b': 2}) k = d.keys() self.assert_('a' in k) self.assert_('b' in k) self.assert_('c' not in k) def test_values(self): BasicTestMappingProtocol.test_values(self) d = self._full_mapping({1:2}) self.assertEqual(d.values(), [2]) def test_items(self): BasicTestMappingProtocol.test_items(self) d = self._full_mapping({1:2}) self.assertEqual(d.items(), [(1, 2)]) def test_has_key(self): d = self._empty_mapping() self.assert_(not d.has_key('a')) d = self._full_mapping({'a': 1, 'b': 2}) k = d.keys() k.sort() self.assertEqual(k, ['a', 'b']) self.assertRaises(TypeError, d.has_key) def test_contains(self): d = self._empty_mapping() self.assert_(not ('a' in d)) self.assert_('a' not in d) d = self._full_mapping({'a': 1, 'b': 2}) self.assert_('a' in d) self.assert_('b' in d) self.assert_('c' not in d) self.assertRaises(TypeError, d.__contains__) def test_len(self): BasicTestMappingProtocol.test_len(self) d = self._full_mapping({'a': 1, 'b': 2}) self.assertEqual(len(d), 2) def test_getitem(self): BasicTestMappingProtocol.test_getitem(self) d = self._full_mapping({'a': 1, 'b': 2}) self.assertEqual(d['a'], 1) self.assertEqual(d['b'], 2) d['c'] = 3 d['a'] = 4 self.assertEqual(d['c'], 3) self.assertEqual(d['a'], 4) del d['b'] self.assertEqual(d, {'a': 4, 'c': 3}) self.assertRaises(TypeError, d.__getitem__) def test_clear(self): d = self._full_mapping({1:1, 2:2, 3:3}) d.clear() self.assertEqual(d, {}) self.assertRaises(TypeError, d.clear, None) def test_update(self): BasicTestMappingProtocol.test_update(self) # mapping argument d = self._empty_mapping() d.update({1:100}) d.update({2:20}) d.update({1:1, 2:2, 3:3}) self.assertEqual(d, {1:1, 2:2, 3:3}) # no argument d.update() self.assertEqual(d, {1:1, 2:2, 3:3}) # keyword arguments d = self._empty_mapping() d.update(x=100) d.update(y=20) d.update(x=1, y=2, z=3) self.assertEqual(d, {"x":1, "y":2, "z":3}) # item sequence d = self._empty_mapping() d.update([("x", 100), ("y", 20)]) self.assertEqual(d, {"x":100, "y":20}) # Both item sequence and keyword arguments d = self._empty_mapping() d.update([("x", 100), ("y", 20)], x=1, y=2) self.assertEqual(d, {"x":1, "y":2}) # iterator d = self._full_mapping({1:3, 2:4}) d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems()) self.assertEqual(d, {1:2, 2:4, 3:4, 5:6}) class SimpleUserDict: def __init__(self): self.d = {1:1, 2:2, 3:3} def keys(self): return self.d.keys() def __getitem__(self, i): return self.d[i] d.clear() d.update(SimpleUserDict()) self.assertEqual(d, {1:1, 2:2, 3:3}) def test_fromkeys(self): self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = self._empty_mapping() self.assert_(not(d.fromkeys('abc') is d)) self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) self.assertEqual(d.fromkeys([]), {}) def g(): yield 1 self.assertEqual(d.fromkeys(g()), {1:None}) self.assertRaises(TypeError, {}.fromkeys, 3) class dictlike(self.type2test): pass self.assertEqual(dictlike.fromkeys('a'), {'a':None}) self.assertEqual(dictlike().fromkeys('a'), {'a':None}) self.assert_(dictlike.fromkeys('a').__class__ is dictlike) self.assert_(dictlike().fromkeys('a').__class__ is dictlike) # FIXME: the following won't work with UserDict, because it's an old style class # self.assert_(type(dictlike.fromkeys('a')) is dictlike) class mydict(self.type2test): def __new__(cls): return UserDict.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) # FIXME: the following won't work with UserDict, because it's an old style class # self.assert_(isinstance(ud, UserDict.UserDict)) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass class baddict1(self.type2test): def __init__(self): raise Exc() self.assertRaises(Exc, baddict1.fromkeys, [1]) class BadSeq(object): def __iter__(self): return self def next(self): raise Exc() self.assertRaises(Exc, self.type2test.fromkeys, BadSeq()) class baddict2(self.type2test): def __setitem__(self, key, value): raise Exc() self.assertRaises(Exc, baddict2.fromkeys, [1]) def test_copy(self): d = self._full_mapping({1:1, 2:2, 3:3}) self.assertEqual(d.copy(), {1:1, 2:2, 3:3}) d = self._empty_mapping() self.assertEqual(d.copy(), d) self.assert_(isinstance(d.copy(), d.__class__)) self.assertRaises(TypeError, d.copy, None) def test_get(self): BasicTestMappingProtocol.test_get(self) d = self._empty_mapping() self.assert_(d.get('c') is None) self.assertEqual(d.get('c', 3), 3) d = self._full_mapping({'a' : 1, 'b' : 2}) self.assert_(d.get('c') is None) self.assertEqual(d.get('c', 3), 3) self.assertEqual(d.get('a'), 1) self.assertEqual(d.get('a', 3), 1) def test_setdefault(self): BasicTestMappingProtocol.test_setdefault(self) d = self._empty_mapping() self.assert_(d.setdefault('key0') is None) d.setdefault('key0', []) self.assert_(d.setdefault('key0') is None) d.setdefault('key', []).append(3) self.assertEqual(d['key'][0], 3) d.setdefault('key', []).append(4) self.assertEqual(len(d['key']), 2) def test_popitem(self): BasicTestMappingProtocol.test_popitem(self) for copymode in -1, +1: # -1: b has same structure as a # +1: b is a.copy() for log2size in range(4): # XXX 12 too large for PyPy size = 2**log2size a = self._empty_mapping() b = self._empty_mapping() for i in range(size): a[repr(i)] = i if copymode < 0: b[repr(i)] = i if copymode > 0: b = a.copy() for i in range(size): ka, va = ta = a.popitem() self.assertEqual(va, int(ka)) kb, vb = tb = b.popitem() self.assertEqual(vb, int(kb)) self.assert_(not(copymode < 0 and ta != tb)) self.assert_(not a) self.assert_(not b) def test_pop(self): BasicTestMappingProtocol.test_pop(self) # Tests for pop with specified key d = self._empty_mapping() k, v = 'abc', 'def' # verify longs/ints get same value when key > 32 bits (for 64-bit archs) # see SF bug #689659 x = 4503599627370496L y = 4503599627370496 h = self._full_mapping({x: 'anything', y: 'something else'}) self.assertEqual(h[x], h[y]) self.assertEqual(d.pop(k, v), v) d[k] = v self.assertEqual(d.pop(k, 1), v) class TestHashMappingProtocol(TestMappingProtocol): def test_getitem(self): TestMappingProtocol.test_getitem(self) class Exc(Exception): pass class BadEq(object): def __eq__(self, other): raise Exc() d = self._empty_mapping() d[BadEq()] = 42 self.assertRaises(KeyError, d.__getitem__, 23) class BadHash(object): fail = False def __hash__(self): if self.fail: raise Exc() else: return 42 d = self._empty_mapping() x = BadHash() d[x] = 42 x.fail = True self.assertRaises(Exc, d.__getitem__, x) def test_fromkeys(self): TestMappingProtocol.test_fromkeys(self) class mydict(self.type2test): def __new__(cls): return UserDict.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) self.assert_(isinstance(ud, UserDict.UserDict)) def test_pop(self): TestMappingProtocol.test_pop(self) class Exc(Exception): pass class BadHash(object): fail = False def __hash__(self): if self.fail: raise Exc() else: return 42 d = self._empty_mapping() x = BadHash() d[x] = 42 x.fail = True self.assertRaises(Exc, d.pop, x) def test_mutatingiteration(self): d = self._empty_mapping() d[1] = 1 try: for i in d: d[i+1] = 1 except RuntimeError: pass else: self.fail("changing dict size during iteration doesn't raise Error") def test_repr(self): d = self._empty_mapping() self.assertEqual(repr(d), '{}') d[1] = 2 self.assertEqual(repr(d), '{1: 2}') d = self._empty_mapping() d[1] = d self.assertEqual(repr(d), '{1: {...}}') class Exc(Exception): pass class BadRepr(object): def __repr__(self): raise Exc() d = self._full_mapping({1: BadRepr()}) self.assertRaises(Exc, repr, d) def test_le(self): self.assert_(not (self._empty_mapping() < self._empty_mapping())) self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L}))) class Exc(Exception): pass class BadCmp(object): def __cmp__(self, other): raise Exc() d1 = self._full_mapping({BadCmp(): 1}) d2 = self._full_mapping({1: 1}) try: d1 < d2 except Exc: pass else: self.fail("< didn't raise Exc") def test_setdefault(self): TestMappingProtocol.test_setdefault(self) class Exc(Exception): pass class BadHash(object): fail = False def __hash__(self): if self.fail: raise Exc() else: return 42 d = self._empty_mapping() x = BadHash() d[x] = 42 x.fail = True self.assertRaises(Exc, d.setdefault, x, [])
Python
""" This package only contains the tests that we have modified for PyPy. It uses the 'official' hack to include the rest of the standard 'test' package from CPython. This assumes that sys.path is configured to contain 'lib-python/modified-2.4.1' before 'lib-python/2.4.1'. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Python
""" Tests common to list and UserList.UserList """ import sys import os import unittest from test import test_support, seq_tests class CommonTest(seq_tests.CommonTest): def test_init(self): # Iterable arg is optional self.assertEqual(self.type2test([]), self.type2test()) # Init clears previous values a = self.type2test([1, 2, 3]) a.__init__() self.assertEqual(a, self.type2test([])) # Init overwrites previous values a = self.type2test([1, 2, 3]) a.__init__([4, 5, 6]) self.assertEqual(a, self.type2test([4, 5, 6])) # Mutables always return a new object b = self.type2test(a) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) def test_repr(self): l0 = [] l2 = [0, 1, 2] a0 = self.type2test(l0) a2 = self.type2test(l2) self.assertEqual(str(a0), str(l0)) self.assertEqual(repr(a0), repr(l0)) self.assertEqual(`a2`, `l2`) self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]") a2.append(a2) a2.append(3) self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") def test_print(self): d = self.type2test(xrange(200)) d.append(d) d.extend(xrange(200,400)) d.append(d) d.append(400) try: fo = open(test_support.TESTFN, "wb") print >> fo, d, fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(d)) finally: fo.close() os.remove(test_support.TESTFN) def test_set_subscript(self): a = self.type2test(range(20)) self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 0), [1,2,3]) self.assertRaises(TypeError, a.__setitem__, slice(0, 10), 1) self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 2), [1,2]) self.assertRaises(TypeError, a.__getitem__, 'x', 1) a[slice(2,10,3)] = [1,2,3] self.assertEqual(a, self.type2test([0, 1, 1, 3, 4, 2, 6, 7, 3, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])) def test_reversed(self): a = self.type2test(range(20)) r = reversed(a) self.assertEqual(list(r), self.type2test(range(19, -1, -1))) self.assertRaises(StopIteration, r.next) self.assertEqual(list(reversed(self.type2test())), self.type2test()) def test_setitem(self): a = self.type2test([0, 1]) a[0] = 0 a[1] = 100 self.assertEqual(a, self.type2test([0, 100])) a[-1] = 200 self.assertEqual(a, self.type2test([0, 200])) a[-2] = 100 self.assertEqual(a, self.type2test([100, 200])) self.assertRaises(IndexError, a.__setitem__, -3, 200) self.assertRaises(IndexError, a.__setitem__, 2, 200) a = self.type2test([]) self.assertRaises(IndexError, a.__setitem__, 0, 200) self.assertRaises(IndexError, a.__setitem__, -1, 200) self.assertRaises(TypeError, a.__setitem__) a = self.type2test([0,1,2,3,4]) a[0L] = 1 a[1L] = 2 a[2L] = 3 self.assertEqual(a, self.type2test([1,2,3,3,4])) a[0] = 5 a[1] = 6 a[2] = 7 self.assertEqual(a, self.type2test([5,6,7,3,4])) a[-2L] = 88 a[-1L] = 99 self.assertEqual(a, self.type2test([5,6,7,88,99])) a[-2] = 8 a[-1] = 9 self.assertEqual(a, self.type2test([5,6,7,8,9])) def test_delitem(self): a = self.type2test([0, 1]) del a[1] self.assertEqual(a, [0]) del a[0] self.assertEqual(a, []) a = self.type2test([0, 1]) del a[-2] self.assertEqual(a, [1]) del a[-1] self.assertEqual(a, []) a = self.type2test([0, 1]) self.assertRaises(IndexError, a.__delitem__, -3) self.assertRaises(IndexError, a.__delitem__, 2) a = self.type2test([]) self.assertRaises(IndexError, a.__delitem__, 0) self.assertRaises(TypeError, a.__delitem__) def test_setslice(self): l = [0, 1] a = self.type2test(l) for i in range(-3, 4): a[:i] = l[:i] self.assertEqual(a, l) a2 = a[:] a2[:i] = a[:i] self.assertEqual(a2, a) a[i:] = l[i:] self.assertEqual(a, l) a2 = a[:] a2[i:] = a[i:] self.assertEqual(a2, a) for j in range(-3, 4): a[i:j] = l[i:j] self.assertEqual(a, l) a2 = a[:] a2[i:j] = a[i:j] self.assertEqual(a2, a) aa2 = a2[:] aa2[:0] = [-2, -1] self.assertEqual(aa2, [-2, -1, 0, 1]) aa2[0:] = [] self.assertEqual(aa2, []) a = self.type2test([1, 2, 3, 4, 5]) a[:-1] = a self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 5])) a = self.type2test([1, 2, 3, 4, 5]) a[1:] = a self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5])) a = self.type2test([1, 2, 3, 4, 5]) a[1:-1] = a self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5, 5])) a = self.type2test([]) a[:] = tuple(range(10)) self.assertEqual(a, self.type2test(range(10))) if hasattr(a, '__setslice__'): self.assertRaises(TypeError, a.__setslice__, 0, 1, 5) self.assertRaises(TypeError, a.__setslice__) def test_delslice(self): a = self.type2test([0, 1]) del a[1:2] del a[0:1] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) del a[1L:2L] del a[0L:1L] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) del a[-2:-1] self.assertEqual(a, self.type2test([1])) a = self.type2test([0, 1]) del a[-2L:-1L] self.assertEqual(a, self.type2test([1])) a = self.type2test([0, 1]) del a[1:] del a[:1] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) del a[1L:] del a[:1L] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) del a[-1:] self.assertEqual(a, self.type2test([0])) a = self.type2test([0, 1]) del a[-1L:] self.assertEqual(a, self.type2test([0])) a = self.type2test([0, 1]) del a[:] self.assertEqual(a, self.type2test([])) def test_append(self): a = self.type2test([]) a.append(0) a.append(1) a.append(2) self.assertEqual(a, self.type2test([0, 1, 2])) self.assertRaises(TypeError, a.append) def test_extend(self): a1 = self.type2test([0]) a2 = self.type2test((0, 1)) a = a1[:] a.extend(a2) self.assertEqual(a, a1 + a2) a.extend(self.type2test([])) self.assertEqual(a, a1 + a2) a.extend(a) self.assertEqual(a, self.type2test([0, 0, 1, 0, 0, 1])) a = self.type2test("spam") a.extend("eggs") self.assertEqual(a, list("spameggs")) self.assertRaises(TypeError, a.extend, None) self.assertRaises(TypeError, a.extend) def test_insert(self): a = self.type2test([0, 1, 2]) a.insert(0, -2) a.insert(1, -1) a.insert(2, 0) self.assertEqual(a, [-2, -1, 0, 0, 1, 2]) b = a[:] b.insert(-2, "foo") b.insert(-200, "left") b.insert(200, "right") self.assertEqual(b, self.type2test(["left",-2,-1,0,0,"foo",1,2,"right"])) self.assertRaises(TypeError, a.insert) def test_pop(self): from decimal import Decimal a = self.type2test([-1, 0, 1]) a.pop() self.assertEqual(a, [-1, 0]) a.pop(0) self.assertEqual(a, [0]) self.assertRaises(IndexError, a.pop, 5) a.pop(0) self.assertEqual(a, []) self.assertRaises(IndexError, a.pop) self.assertRaises(TypeError, a.pop, 42, 42) a = self.type2test([0, 10, 20, 30, 40]) # xxx Decimal make a bad index as much as float # also l[Decimal(2)] doesn't work, what to make of this? #self.assertEqual(a.pop(Decimal(2)), 20) #self.assertRaises(IndexError, a.pop, Decimal(25)) def test_remove(self): a = self.type2test([0, 0, 1]) a.remove(1) self.assertEqual(a, [0, 0]) a.remove(0) self.assertEqual(a, [0]) a.remove(0) self.assertEqual(a, []) self.assertRaises(ValueError, a.remove, 0) self.assertRaises(TypeError, a.remove) class BadExc(Exception): pass class BadCmp: def __eq__(self, other): if other == 2: raise BadExc() return False a = self.type2test([0, 1, 2, 3]) self.assertRaises(BadExc, a.remove, BadCmp()) def test_count(self): a = self.type2test([0, 1, 2])*3 self.assertEqual(a.count(0), 3) self.assertEqual(a.count(1), 3) self.assertEqual(a.count(3), 0) self.assertRaises(TypeError, a.count) class BadExc(Exception): pass class BadCmp: def __eq__(self, other): if other == 2: raise BadExc() return False self.assertRaises(BadExc, a.count, BadCmp()) def test_index(self): u = self.type2test([0, 1]) self.assertEqual(u.index(0), 0) self.assertEqual(u.index(1), 1) self.assertRaises(ValueError, u.index, 2) u = self.type2test([-2, -1, 0, 0, 1, 2]) self.assertEqual(u.count(0), 2) self.assertEqual(u.index(0), 2) self.assertEqual(u.index(0, 2), 2) self.assertEqual(u.index(-2, -10), 0) self.assertEqual(u.index(0, 3), 3) self.assertEqual(u.index(0, 3, 4), 3) self.assertRaises(ValueError, u.index, 2, 0, -10) self.assertRaises(TypeError, u.index) class BadExc(Exception): pass class BadCmp: def __eq__(self, other): if other == 2: raise BadExc() return False a = self.type2test([0, 1, 2, 3]) self.assertRaises(BadExc, a.index, BadCmp()) a = self.type2test([-2, -1, 0, 0, 1, 2]) self.assertEqual(a.index(0), 2) self.assertEqual(a.index(0, 2), 2) self.assertEqual(a.index(0, -4), 2) self.assertEqual(a.index(-2, -10), 0) self.assertEqual(a.index(0, 3), 3) self.assertEqual(a.index(0, -3), 3) self.assertEqual(a.index(0, 3, 4), 3) self.assertEqual(a.index(0, -3, -2), 3) self.assertEqual(a.index(0, -4*sys.maxint, 4*sys.maxint), 2) self.assertRaises(ValueError, a.index, 0, 4*sys.maxint,-4*sys.maxint) self.assertRaises(ValueError, a.index, 2, 0, -10) a.remove(0) self.assertRaises(ValueError, a.index, 2, 0, 4) self.assertEqual(a, self.type2test([-2, -1, 0, 1, 2])) # Test modifying the list during index's iteration class EvilCmp: def __init__(self, victim): self.victim = victim def __eq__(self, other): del self.victim[:] return False a = self.type2test() a[:] = [EvilCmp(a) for _ in xrange(100)] # This used to seg fault before patch #1005778 self.assertRaises(ValueError, a.index, None) def test_reverse(self): u = self.type2test([-2, -1, 0, 1, 2]) u2 = u[:] u.reverse() self.assertEqual(u, [2, 1, 0, -1, -2]) u.reverse() self.assertEqual(u, u2) self.assertRaises(TypeError, u.reverse, 42) def test_sort(self): u = self.type2test([1, 0]) u.sort() self.assertEqual(u, [0, 1]) u = self.type2test([2,1,0,-1,-2]) u.sort() self.assertEqual(u, self.type2test([-2,-1,0,1,2])) self.assertRaises(TypeError, u.sort, 42, 42) def revcmp(a, b): return cmp(b, a) u.sort(revcmp) self.assertEqual(u, self.type2test([2,1,0,-1,-2])) # The following dumps core in unpatched Python 1.5: def myComparison(x,y): return cmp(x%3, y%7) z = self.type2test(range(12)) z.sort(myComparison) self.assertRaises(TypeError, z.sort, 2) def selfmodifyingComparison(x,y): z.append(1) return cmp(x, y) self.assertRaises(ValueError, z.sort, selfmodifyingComparison) self.assertRaises(TypeError, z.sort, lambda x, y: 's') self.assertRaises(TypeError, z.sort, 42, 42, 42, 42) def test_slice(self): u = self.type2test("spam") u[:2] = "h" self.assertEqual(u, list("ham")) def test_iadd(self): super(CommonTest, self).test_iadd() u = self.type2test([0, 1]) u2 = u u += [2, 3] self.assert_(u is u2) u = self.type2test("spam") u += "eggs" self.assertEqual(u, self.type2test("spameggs")) self.assertRaises(TypeError, u.__iadd__, None) def test_imul(self): u = self.type2test([0, 1]) u *= 3 self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1])) u *= 0 self.assertEqual(u, self.type2test([])) s = self.type2test([]) oldid = id(s) s *= 10 self.assertEqual(id(s), oldid) def test_extendedslicing(self): # subscript a = self.type2test([0,1,2,3,4]) # deletion del a[::2] self.assertEqual(a, self.type2test([1,3])) a = self.type2test(range(5)) del a[1::2] self.assertEqual(a, self.type2test([0,2,4])) a = self.type2test(range(5)) del a[1::-2] self.assertEqual(a, self.type2test([0,2,3,4])) a = self.type2test(range(10)) del a[::1000] self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 6, 7, 8, 9])) # assignment a = self.type2test(range(10)) a[::2] = [-1]*5 self.assertEqual(a, self.type2test([-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])) a = self.type2test(range(10)) a[::-4] = [10]*3 self.assertEqual(a, self.type2test([0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])) a = self.type2test(range(4)) a[::-1] = a self.assertEqual(a, self.type2test([3, 2, 1, 0])) a = self.type2test(range(10)) b = a[:] c = a[:] a[2:3] = self.type2test(["two", "elements"]) b[slice(2,3)] = self.type2test(["two", "elements"]) c[2:3:] = self.type2test(["two", "elements"]) self.assertEqual(a, b) self.assertEqual(a, c) a = self.type2test(range(10)) a[::2] = tuple(range(5)) self.assertEqual(a, self.type2test([0, 1, 1, 3, 2, 5, 3, 7, 4, 9]))
Python
import autopath import py, os from pypy.config.config import OptionDescription, BoolOption, IntOption, ArbitraryOption, FloatOption from pypy.config.config import ChoiceOption, StrOption, to_optparse, Config DEFL_INLINE_THRESHOLD = 32.4 # just enough to inline add__Int_Int() # and just small enough to prevend inlining of some rlist functions. DEFL_PROF_BASED_INLINE_THRESHOLD = 32.4 DEFL_CLEVER_MALLOC_REMOVAL_INLINE_THRESHOLD = 32.4 translation_optiondescription = OptionDescription( "translation", "Translation Options", [ BoolOption("stackless", "enable stackless features during compilation", default=False, cmdline="--stackless", requires=[("translation.type_system", "lltype")]), ChoiceOption("type_system", "Type system to use when RTyping", ["lltype", "ootype"], cmdline=None, requires={ "ootype": [("translation.backendopt.raisingop2direct_call", False), ("translation.backendopt.constfold", False), ("translation.backendopt.heap2stack", False), ("translation.backendopt.clever_malloc_removal", False)] }), ChoiceOption("backend", "Backend to use for code generation", ["c", "llvm", "cli", "jvm", "js", "squeak", "cl"], requires={ "c": [("translation.type_system", "lltype")], "llvm": [("translation.type_system", "lltype"), ("translation.gc", "boehm"), ("translation.backendopt.raisingop2direct_call", True)], "cli": [("translation.type_system", "ootype")], "jvm": [("translation.type_system", "ootype")], "js": [("translation.type_system", "ootype")], "squeak": [("translation.type_system", "ootype")], "cl": [("translation.type_system", "ootype")], }, cmdline="-b --backend"), BoolOption("llvm_via_c", "compile llvm via C", default=False, cmdline="--llvm-via-c", requires=[("translation.backend", "llvm")]), ChoiceOption("gc", "Garbage Collection Strategy", ["boehm", "ref", "framework", "none", "stacklessgc", "exact_boehm"], "ref", requires={ "stacklessgc": [("translation.stackless", True)]}, cmdline="--gc"), BoolOption("thread", "enable use of threading primitives", default=False, cmdline="--thread"), BoolOption("verbose", "Print extra information", default=False), BoolOption("debug", "Record extra annotation information", cmdline="-d --debug", default=False), BoolOption("insist", "Try hard to go on RTyping", default=False, cmdline="--insist"), IntOption("withsmallfuncsets", "Represent groups of less funtions than this as indices into an array", default=0), BoolOption("countmallocs", "Count mallocs and frees", default=False, cmdline=None), # misc StrOption("cc", "Specify compiler to use for compiling generated C", cmdline="--cc"), StrOption("profopt", "Specify profile based optimization script", cmdline="--profopt"), BoolOption("noprofopt", "Don't use profile based optimization", default=False, cmdline="--no-profopt", negation=False), BoolOption("instrument", "internal: turn instrumentation on", default=False, cmdline=None), ArbitraryOption("instrumentctl", "internal", default=None), StrOption("output", "Output file name", cmdline="--output"), # portability options BoolOption("vanilla", "Try to be as portable as possible, which is not much", default=False, cmdline="--vanilla", requires=[("translation.no__thread", True)]), BoolOption("no__thread", "don't use __thread for implementing TLS", default=False, cmdline="--no__thread", negation=False), StrOption("compilerflags", "Specify flags for the C compiler", cmdline="--cflags"), StrOption("linkerflags", "Specify flags for the linker (C backend only)", cmdline="--ldflags"), # Flags of the TranslationContext: BoolOption("simplifying", "Simplify flow graphs", default=True), BoolOption("builtins_can_raise_exceptions", "When true, assume any call to a 'simple' builtin such as " "'hex' can raise an arbitrary exception", default=False, cmdline=None), BoolOption("list_comprehension_operations", "When true, look for and special-case the sequence of " "operations that results from a list comprehension and " "attempt to pre-allocate the list", default=False, cmdline=None), ChoiceOption("fork_before", "(UNIX) Create restartable checkpoint before step", ["annotate", "rtype", "backendopt", "database", "source", "hintannotate", "timeshift"], default=None, cmdline="--fork-before"), # options for ootype OptionDescription("ootype", "Object Oriented Typesystem options", [ BoolOption("mangle", "Mangle names of class members", default=True), ]), OptionDescription("backendopt", "Backend Optimization Options", [ # control inlining BoolOption("inline", "Do basic inlining and malloc removal", default=True), FloatOption("inline_threshold", "Threshold when to inline functions", default=DEFL_INLINE_THRESHOLD, cmdline="--inline-threshold"), StrOption("inline_heuristic", "Dotted name of an heuristic function " "for inlining", default="pypy.translator.backendopt.inline.inlining_heuristic", cmdline="--inline-heuristic"), BoolOption("print_statistics", "Print statistics while optimizing", default=False), BoolOption("merge_if_blocks", "Merge if ... elif chains", cmdline="--if-block-merge", default=True), BoolOption("raisingop2direct_call", "Transform operations that can implicitly raise an " "exception into calls to functions that explicitly " "raise exceptions", default=False, cmdline="--raisingop2direct_call"), BoolOption("mallocs", "Remove mallocs", default=True), BoolOption("constfold", "Constant propagation", default=True), BoolOption("heap2stack", "Escape analysis and stack allocation", default=False, requires=[("translation.stackless", False)]), # control profile based inlining StrOption("profile_based_inline", "Use call count profiling to drive inlining" ", specify arguments", default=None, cmdline="--prof-based-inline"), FloatOption("profile_based_inline_threshold", "Threshold when to inline functions " "for profile based inlining", default=DEFL_PROF_BASED_INLINE_THRESHOLD, cmdline="--prof-based-inline-threshold"), StrOption("profile_based_inline_heuristic", "Dotted name of an heuristic function " "for profile based inlining", default="pypy.translator.backendopt.inline.inlining_heuristic", cmdline="--prof-based-inline-heuristic"), # control clever malloc removal BoolOption("clever_malloc_removal", "Drives inlining to remove mallocs in a clever way", default=False, cmdline="--clever-malloc-removal"), FloatOption("clever_malloc_removal_threshold", "Threshold when to inline functions in " "clever malloc removal", default=DEFL_CLEVER_MALLOC_REMOVAL_INLINE_THRESHOLD, cmdline="--clever-malloc-removal-threshold"), StrOption("clever_malloc_removal_heuristic", "Dotted name of an heuristic function " "for inlining in clever malloc removal", default="pypy.translator.backendopt.inline.inlining_heuristic", cmdline="--clever-malloc-removal-heuristic"), BoolOption("remove_asserts", "Remove operations that look like 'raise AssertionError', " "which lets the C optimizer remove the asserts", default=False), BoolOption("stack_optimization", "Tranform graphs in SSI form into graphs tailored for " "stack based virtual machines (only for backends that support it)", default=True), BoolOption("none", "Do not run any backend optimizations", requires=[('translation.backendopt.inline', False), ('translation.backendopt.inline_threshold', 0), ('translation.backendopt.merge_if_blocks', False), ('translation.backendopt.mallocs', False), ('translation.backendopt.constfold', False)]) ]), OptionDescription("llvm", "GenLLVM options", [ BoolOption("debug", "Include the llops in the source as comments", default=False), BoolOption("logging", "Log how long the various parts of llvm generation take", default=False), BoolOption("isolate", "Peform an isolated import", default=True), ]), OptionDescription("cli", "GenCLI options", [ BoolOption("trace_calls", "Trace function calls", default=False, cmdline="--cli-trace-calls") ]), ]) def get_combined_translation_config(other_optdescr=None, existing_config=None, overrides=None, translating=False): if overrides is None: overrides = {} d = BoolOption("translating", "indicates whether we are translating currently", default=False, cmdline=None) if other_optdescr is None: children = [] newname = "" else: children = [other_optdescr] newname = other_optdescr._name if existing_config is None: children += [d, translation_optiondescription] else: children += [child for child in existing_config._cfgimpl_descr._children if child._name != newname] descr = OptionDescription("pypy", "all options", children) config = Config(descr, **overrides) if translating: config.translating = True if existing_config is not None: for child in existing_config._cfgimpl_descr._children: if child._name == newname: continue value = getattr(existing_config, child._name) config._cfgimpl_values[child._name] = value return config
Python
import py from py.compat import optparse from pypy.tool.pairtype import extendabletype SUPPRESS_USAGE = optparse.SUPPRESS_USAGE class AmbigousOptionError(Exception): pass class NoMatchingOptionFound(AttributeError): pass class Config(object): _cfgimpl_frozen = False def __init__(self, descr, parent=None, **overrides): self._cfgimpl_descr = descr self._cfgimpl_value_owners = {} self._cfgimpl_parent = parent self._cfgimpl_values = {} self._cfgimpl_build(overrides) def _cfgimpl_build(self, overrides): for child in self._cfgimpl_descr._children: if isinstance(child, Option): self._cfgimpl_values[child._name] = child.getdefault() self._cfgimpl_value_owners[child._name] = 'default' elif isinstance(child, OptionDescription): self._cfgimpl_values[child._name] = Config(child, parent=self) self.override(overrides) def override(self, overrides): for name, value in overrides.iteritems(): homeconfig, name = self._cfgimpl_get_home_by_path(name) homeconfig.setoption(name, value, 'default') def copy(self, as_default=False, parent=None): result = Config.__new__(self.__class__) result._cfgimpl_descr = self._cfgimpl_descr result._cfgimpl_value_owners = owners = {} result._cfgimpl_parent = parent result._cfgimpl_values = v = {} for child in self._cfgimpl_descr._children: if isinstance(child, Option): v[child._name] = self._cfgimpl_values[child._name] if as_default: owners[child._name] = 'default' else: owners[child._name] = ( self._cfgimpl_value_owners[child._name]) elif isinstance(child, OptionDescription): v[child._name] = self._cfgimpl_values[child._name].copy( as_default, parent=result) return result def __setattr__(self, name, value): if self._cfgimpl_frozen and getattr(self, name) != value: raise TypeError("trying to change a frozen option object") if name.startswith('_cfgimpl_'): self.__dict__[name] = value return self.setoption(name, value, 'user') def __getattr__(self, name): if '.' in name: homeconfig, name = self._cfgimpl_get_home_by_path(name) return getattr(homeconfig, name) if name.startswith('_cfgimpl_'): # if it were in __dict__ it would have been found already raise AttributeError("%s object has no attribute %s" % (self.__class__, name)) if name not in self._cfgimpl_values: raise AttributeError("%s object has no attribute %s" % (self.__class__, name)) return self._cfgimpl_values[name] def __delattr__(self, name): # XXX if you use delattr you are responsible for all bad things # happening if name.startswith('_cfgimpl_'): del self.__dict__[name] return self._cfgimpl_value_owners[name] = 'default' opt = getattr(self._cfgimpl_descr, name) if isinstance(opt, OptionDescription): raise AttributeError("can't option subgroup") self._cfgimpl_values[name] = getattr(opt, 'default', None) def setoption(self, name, value, who): if name not in self._cfgimpl_values: raise AttributeError('unknown option %s' % (name,)) child = getattr(self._cfgimpl_descr, name) oldowner = self._cfgimpl_value_owners[child._name] oldvalue = getattr(self, name) if oldvalue != value and oldowner not in ("default", "suggested"): if who in ("default", "suggested"): return raise ValueError('cannot override value to %s for option %s' % (value, name)) child.setoption(self, value, who) self._cfgimpl_value_owners[name] = who def set(self, **kwargs): all_paths = [p.split(".") for p in self.getpaths()] for key, value in kwargs.iteritems(): key_p = key.split('.') candidates = [p for p in all_paths if p[-len(key_p):] == key_p] if len(candidates) == 1: name = '.'.join(candidates[0]) homeconfig, name = self._cfgimpl_get_home_by_path(name) homeconfig.setoption(name, value, "user") elif len(candidates) > 1: raise AmbigousOptionError( 'more than one option that ends with %s' % (key, )) else: raise NoMatchingOptionFound( 'there is no option that matches %s' % (key, )) def _cfgimpl_get_home_by_path(self, path): """returns tuple (config, name)""" path = path.split('.') for step in path[:-1]: self = getattr(self, step) return self, path[-1] def _cfgimpl_get_toplevel(self): while self._cfgimpl_parent is not None: self = self._cfgimpl_parent return self def _freeze_(self): self.__dict__['_cfgimpl_frozen'] = True return True def getkey(self): return self._cfgimpl_descr.getkey(self) def __hash__(self): return hash(self.getkey()) def __eq__(self, other): return self.getkey() == other.getkey() def __ne__(self, other): return not self == other def __iter__(self): for child in self._cfgimpl_descr._children: if isinstance(child, Option): yield child._name, getattr(self, child._name) def __str__(self, indent=""): lines = [] children = [(child._name, child) for child in self._cfgimpl_descr._children] children.sort() for name, child in children: if self._cfgimpl_value_owners.get(name, None) == 'default': continue value = getattr(self, name) if isinstance(value, Config): substr = value.__str__(indent + " ") else: substr = "%s %s = %s" % (indent, name, value) if substr: lines.append(substr) if indent and not lines: return '' # hide subgroups with all default values lines.insert(0, "%s[%s]" % (indent, self._cfgimpl_descr._name,)) return '\n'.join(lines) def getpaths(self, include_groups=False): """returns a list of all paths in self, recursively """ return self._cfgimpl_descr.getpaths(include_groups=include_groups) DEFAULT_OPTION_NAME = object() class Option(object): __metaclass__ = extendabletype def __init__(self, name, doc, cmdline=DEFAULT_OPTION_NAME): self._name = name self.doc = doc self.cmdline = cmdline def validate(self, value): raise NotImplementedError('abstract base class') def getdefault(self): return self.default def setoption(self, config, value, who): name = self._name if who == "default" and value is None: pass elif not self.validate(value): raise ValueError('invalid value %s for option %s' % (value, name)) config._cfgimpl_values[name] = value def getkey(self, value): return value def convert_from_cmdline(self, value): return value def add_optparse_option(self, argnames, parser, config): callback = ConfigUpdate(config, self) option = parser.add_option(help=self.doc+" %default", action='callback', type=self.opt_type, callback=callback, metavar=self._name.upper(), *argnames) class ChoiceOption(Option): opt_type = 'string' def __init__(self, name, doc, values, default=None, requires=None, cmdline=DEFAULT_OPTION_NAME): super(ChoiceOption, self).__init__(name, doc, cmdline) self.values = values self.default = default if requires is None: requires = {} self._requires = requires def setoption(self, config, value, who): name = self._name for path, reqvalue in self._requires.get(value, []): toplevel = config._cfgimpl_get_toplevel() homeconfig, name = toplevel._cfgimpl_get_home_by_path(path) homeconfig.setoption(name, reqvalue, who) super(ChoiceOption, self).setoption(config, value, who) def validate(self, value): return value is None or value in self.values def convert_from_cmdline(self, value): return value.strip() def _getnegation(optname): if optname.startswith("without"): return "with" + optname[len("without"):] if optname.startswith("with"): return "without" + optname[len("with"):] return "no-" + optname class BoolOption(Option): def __init__(self, name, doc, default=None, requires=None, suggests=None, cmdline=DEFAULT_OPTION_NAME, negation=True): super(BoolOption, self).__init__(name, doc, cmdline=cmdline) self._requires = requires self._suggests = suggests self.default = default self.negation = negation def validate(self, value): return isinstance(value, bool) def setoption(self, config, value, who): name = self._name if value and self._requires is not None: for path, reqvalue in self._requires: toplevel = config._cfgimpl_get_toplevel() homeconfig, name = toplevel._cfgimpl_get_home_by_path(path) homeconfig.setoption(name, reqvalue, who) if value and self._suggests is not None: for path, reqvalue in self._suggests: toplevel = config._cfgimpl_get_toplevel() homeconfig, name = toplevel._cfgimpl_get_home_by_path(path) homeconfig.setoption(name, reqvalue, "suggested") super(BoolOption, self).setoption(config, value, who) def add_optparse_option(self, argnames, parser, config): callback = BoolConfigUpdate(config, self, True) option = parser.add_option(help=self.doc+" %default", action='callback', callback=callback, *argnames) if not self.negation: return no_argnames = ["--" + _getnegation(argname.lstrip("-")) for argname in argnames if argname.startswith("--")] if len(no_argnames) == 0: no_argnames = ["--" + _getnegation(argname.lstrip("-")) for argname in argnames] callback = BoolConfigUpdate(config, self, False) option = parser.add_option(help="unset option set by %s %%default" % (argname, ), action='callback', callback=callback, *no_argnames) class IntOption(Option): opt_type = 'int' def __init__(self, name, doc, default=None, cmdline=DEFAULT_OPTION_NAME): super(IntOption, self).__init__(name, doc, cmdline) self.default = default def validate(self, value): try: int(value) except TypeError: return False return True def setoption(self, config, value, who): try: super(IntOption, self).setoption(config, int(value), who) except TypeError, e: raise ValueError(*e.args) class FloatOption(Option): opt_type = 'float' def __init__(self, name, doc, default=None, cmdline=DEFAULT_OPTION_NAME): super(FloatOption, self).__init__(name, doc, cmdline) self.default = default def validate(self, value): try: float(value) except TypeError: return False return True def setoption(self, config, value, who): try: super(FloatOption, self).setoption(config, float(value), who) except TypeError, e: raise ValueError(*e.args) class StrOption(Option): opt_type = 'string' def __init__(self, name, doc, default=None, cmdline=DEFAULT_OPTION_NAME): super(StrOption, self).__init__(name, doc, cmdline) self.default = default def validate(self, value): return isinstance(value, str) def setoption(self, config, value, who): try: super(StrOption, self).setoption(config, value, who) except TypeError, e: raise ValueError(*e.args) class ArbitraryOption(Option): def __init__(self, name, doc, default=None, defaultfactory=None): super(ArbitraryOption, self).__init__(name, doc, cmdline=None) self.default = default self.defaultfactory = defaultfactory if defaultfactory is not None: assert default is None def validate(self, value): return True def add_optparse_option(self, *args, **kwargs): return def getdefault(self): if self.defaultfactory is not None: return self.defaultfactory() return self.default class OptionDescription(object): __metaclass__ = extendabletype cmdline = None def __init__(self, name, doc, children): self._name = name self.doc = doc self._children = children self._build() def _build(self): for child in self._children: setattr(self, child._name, child) def getkey(self, config): return tuple([child.getkey(getattr(config, child._name)) for child in self._children]) def add_optparse_option(self, argnames, parser, config): return def getpaths(self, include_groups=False, currpath=None): """returns a list of all paths in self, recursively currpath should not be provided (helps with recursion) """ if currpath is None: currpath = [] paths = [] for option in self._children: attr = option._name if attr.startswith('_cfgimpl'): continue value = getattr(self, attr) if isinstance(value, OptionDescription): if include_groups: paths.append('.'.join(currpath + [attr])) currpath.append(attr) paths += value.getpaths(include_groups=include_groups, currpath=currpath) currpath.pop() else: paths.append('.'.join(currpath + [attr])) return paths class OptHelpFormatter(optparse.TitledHelpFormatter): extra_useage = None def expand_default(self, option): assert self.parser dfls = self.parser.defaults defl = "" choices = None if option.action == 'callback' and isinstance(option.callback, ConfigUpdate): callback = option.callback defl = callback.help_default() if isinstance(callback.option, ChoiceOption): choices = callback.option.values else: val = dfls.get(option.dest) if val is None: pass elif isinstance(val, bool): if val is True and option.action=="store_true": defl = "default" else: defl = "default: %s" % val if option.type == 'choice': choices = option.choices if choices is not None: choices = "%s=%s" % (option.metavar, '|'.join(choices)) else: choices = "" if '%default' in option.help: if choices and defl: sep = ", " else: sep = "" defl = '[%s%s%s]' % (choices, sep, defl) if defl == '[]': defl = "" return option.help.replace("%default", defl) elif choices: return option.help + ' [%s]' % choices return option.help def format_usage(self, usage): # XXX bit of a hack result = optparse.TitledHelpFormatter.format_usage(self, usage) if self.extra_useage is not None: return result + "\n" + self.extra_useage + "\n\n" return result class ConfigUpdate(object): def __init__(self, config, option): self.config = config self.option = option def convert_from_cmdline(self, value): return self.option.convert_from_cmdline(value) def __call__(self, option, opt_str, value, parser, *args, **kwargs): try: value = self.convert_from_cmdline(value) self.config.setoption(self.option._name, value, who='cmdline') except ValueError, e: raise optparse.OptionValueError(e.args[0]) def help_default(self): default = getattr(self.config, self.option._name) owner = self.config._cfgimpl_value_owners[self.option._name] if default is None: if owner == 'default': return '' else: default = '???' return "%s: %s" % (owner, default) class BoolConfigUpdate(ConfigUpdate): def __init__(self, config, option, which_value): super(BoolConfigUpdate, self).__init__(config, option) self.which_value = which_value def convert_from_cmdline(self, value): return self.which_value def help_default(self): default = getattr(self.config, self.option._name) owner = self.config._cfgimpl_value_owners[self.option._name] if default == self.which_value: return owner else: return "" def to_optparse(config, useoptions=None, parser=None, parserargs=None, parserkwargs=None, extra_useage=None): grps = {} def get_group(name, doc): steps = name.split('.') if len(steps) < 2: return parser grpname = steps[-2] grp = grps.get(grpname, None) if grp is None: grp = grps[grpname] = parser.add_option_group(doc) return grp if parser is None: if parserargs is None: parserargs = [] if parserkwargs is None: parserkwargs = {} formatter = OptHelpFormatter() formatter.extra_useage = extra_useage parser = optparse.OptionParser( formatter=formatter, *parserargs, **parserkwargs) if useoptions is None: useoptions = config.getpaths(include_groups=True) seen = {} for path in useoptions: if path.endswith(".*"): path = path[:-2] homeconf, name = config._cfgimpl_get_home_by_path(path) subconf = getattr(homeconf, name) children = [ path + "." + child for child in subconf.getpaths()] useoptions.extend(children) else: if path in seen: continue seen[path] = True homeconf, name = config._cfgimpl_get_home_by_path(path) option = getattr(homeconf._cfgimpl_descr, name) if option.cmdline is DEFAULT_OPTION_NAME: chunks = ('--%s' % (path.replace('.', '-'),),) elif option.cmdline is None: continue else: chunks = option.cmdline.split(' ') grp = get_group(path, homeconf._cfgimpl_descr.doc) option.add_optparse_option(chunks, grp, homeconf) return parser def make_dict(config): paths = config.getpaths() options = dict([(path, getattr(config, path)) for path in paths]) return options
Python
import py from py.__.rest.rst import Rest, Paragraph, Strong, ListItem, Title, Link from py.__.rest.rst import Directive, Em, Quote, Text from pypy.config.config import ChoiceOption, BoolOption, StrOption, IntOption from pypy.config.config import FloatOption, OptionDescription, Option, Config from pypy.config.config import ArbitraryOption, DEFAULT_OPTION_NAME from pypy.config.config import _getnegation configdocdir = py.magic.autopath().dirpath().dirpath().join("doc", "config") def get_fullpath(opt, path): if path: return "%s.%s" % (path, opt._name) else: return opt._name def get_cmdline(cmdline, fullpath): if cmdline is DEFAULT_OPTION_NAME: return '--%s' % (fullpath.replace('.', '-'),) else: return cmdline class __extend__(Option): def make_rest_doc(self, path=""): fullpath = get_fullpath(self, path) result = Rest( Title(fullpath, abovechar="=", belowchar="="), Directive("contents"), Paragraph(Link("back to parent", path + ".html")), Title("Basic Option Information"), ListItem(Strong("name:"), self._name), ListItem(Strong("description:"), self.doc)) if self.cmdline is not None: cmdline = get_cmdline(self.cmdline, fullpath) result.add(ListItem(Strong("command-line:"), cmdline)) return result class __extend__(ChoiceOption): def make_rest_doc(self, path=""): content = super(ChoiceOption, self).make_rest_doc(path) content.add(ListItem(Strong("option type:"), "choice option")) content.add(ListItem(Strong("possible values:"), *[ListItem(str(val)) for val in self.values])) if self.default is not None: content.add(ListItem(Strong("default:"), str(self.default))) requirements = [] for val in self.values: if val not in self._requires: continue req = self._requires[val] requirements.append(ListItem("value '%s' requires:" % (val, ), *[ListItem(Link(opt, opt + ".html"), "to be set to '%s'" % (rval, )) for (opt, rval) in req])) if requirements: content.add(ListItem(Strong("requirements:"), *requirements)) return content class __extend__(BoolOption): def make_rest_doc(self, path=""): content = super(BoolOption, self).make_rest_doc(path) fullpath = get_fullpath(self, path) if self.negation and self.cmdline is not None: if self.cmdline is DEFAULT_OPTION_NAME: cmdline = '--%s' % (fullpath.replace('.', '-'),) else: cmdline = self.cmdline neg_cmdline = ["--" + _getnegation(argname.lstrip("-")) for argname in cmdline.split() if argname.startswith("--")][0] content.add(ListItem(Strong("command-line for negation:"), neg_cmdline)) content.add(ListItem(Strong("option type:"), "boolean option")) if self.default is not None: content.add(ListItem(Strong("default:"), str(self.default))) if self._requires is not None: requirements = [ListItem(Link(opt, opt + ".html"), "must be set to '%s'" % (rval, )) for (opt, rval) in self._requires] if requirements: content.add(ListItem(Strong("requirements:"), *requirements)) if self._suggests is not None: suggestions = [ListItem(Link(opt, opt + ".html"), "should be set to '%s'" % (rval, )) for (opt, rval) in self._suggests] if suggestions: content.add(ListItem(Strong("suggestions:"), *suggestions)) return content class __extend__(IntOption): def make_rest_doc(self, path=""): content = super(IntOption, self).make_rest_doc(path) content.add(ListItem(Strong("option type:"), "integer option")) if self.default is not None: content.add(ListItem(Strong("default:"), str(self.default))) return content class __extend__(FloatOption): def make_rest_doc(self, path=""): content = super(FloatOption, self).make_rest_doc(path) content.add(ListItem(Strong("option type:"), "float option")) if self.default is not None: content.add(ListItem(Strong("default:"), str(self.default))) return content class __extend__(StrOption): def make_rest_doc(self, path=""): content = super(StrOption, self).make_rest_doc(path) content.add(ListItem(Strong("option type:"), "string option")) if self.default is not None: content.add(ListItem(Strong("default:"), str(self.default))) return content class __extend__(ArbitraryOption): def make_rest_doc(self, path=""): content = super(ArbitraryOption, self).make_rest_doc(path) content.add(ListItem(Strong("option type:"), "arbitrary option (mostly internal)")) if self.default is not None: content.add(ListItem(Strong("default:"), str(self.default))) elif self.defaultfactory is not None: content.add(ListItem(Strong("factory for the default value:"), str(self.defaultfactory))) return content class __extend__(OptionDescription): def make_rest_doc(self, path=""): fullpath = get_fullpath(self, path) content = Rest( Title(fullpath, abovechar="=", belowchar="="), Directive("contents")) if path: content.add( Paragraph(Link("back to parent", path + ".html"))) content.join( Title("Basic Option Information"), ListItem(Strong("name:"), self._name), ListItem(Strong("description:"), self.doc), Title("Sub-Options")) stack = [] prefix = fullpath curr = content config = Config(self) for ending in self.getpaths(include_groups=True): subpath = fullpath + "." + ending while not (subpath.startswith(prefix) and subpath[len(prefix)] == "."): curr, prefix = stack.pop() print subpath, fullpath, ending, curr sub, step = config._cfgimpl_get_home_by_path(ending) doc = getattr(sub._cfgimpl_descr, step).doc if doc: new = curr.add(ListItem(Link(subpath + ":", subpath + ".html"), Em(doc))) else: new = curr.add(ListItem(Link(subpath + ":", subpath + ".html"))) stack.append((curr, prefix)) prefix = subpath curr = new return content def _get_section_header(cmdline, fullpath, subdescr): # XXX: pypy specific hack txtfile = configdocdir.join(fullpath + ".txt") print txtfile, if not txtfile.check(): print "not found" return "" print "found" content = txtfile.read() if ".. internal" in content: return "Internal Options" return "" def make_cmdline_overview(descr): content = Rest( Title("Overwiew of Command Line Options for '%s'" % (descr._name, ), abovechar="=", belowchar="=")) cmdlines = [] config = Config(descr) for path in config.getpaths(include_groups=False): subconf, step = config._cfgimpl_get_home_by_path(path) fullpath = (descr._name + "." + path) prefix = fullpath.rsplit(".", 1)[0] subdescr = getattr(subconf._cfgimpl_descr, step) cmdline = get_cmdline(subdescr.cmdline, fullpath) if cmdline is not None: header = _get_section_header(cmdline, fullpath, subdescr) cmdlines.append((header, cmdline, fullpath, subdescr)) cmdlines.sort(key=lambda x: (x[0], x[1].strip("-"))) currheader = "" curr = content for header, cmdline, fullpath, subdescr in cmdlines: if header != currheader: content.add(Title(header, abovechar="", belowchar="=")) curr = content.add(Paragraph()) currheader = header curr.add(ListItem(Link(cmdline + ":", fullpath + ".html"), Text(subdescr.doc))) return content
Python
""" self cloning, automatic path configuration copy this into any subdirectory of pypy from which scripts need to be run, typically all of the test subdirs. The idea is that any such script simply issues import autopath and this will make sure that the parent directory containing "pypy" is in sys.path. If you modify the master "autopath.py" version (in pypy/tool/autopath.py) you can directly run it which will copy itself on all autopath.py files it finds under the pypy root directory. This module always provides these attributes: pypydir pypy root directory path this_dir directory where this autopath.py resides """ def __dirinfo(part): """ return (partdir, this_dir) and insert parent of partdir into sys.path. If the parent directories don't have the part an EnvironmentError is raised.""" import sys, os try: head = this_dir = os.path.realpath(os.path.dirname(__file__)) except NameError: head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) while head: partdir = head head, tail = os.path.split(head) if tail == part: break else: raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) pypy_root = os.path.join(head, '') try: sys.path.remove(head) except ValueError: pass sys.path.insert(0, head) munged = {} for name, mod in sys.modules.items(): if '.' in name: continue fn = getattr(mod, '__file__', None) if not isinstance(fn, str): continue newname = os.path.splitext(os.path.basename(fn))[0] if not newname.startswith(part + '.'): continue path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') if path.startswith(pypy_root) and newname != part: modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) if newname != '__init__': modpaths.append(newname) modpath = '.'.join(modpaths) if modpath not in sys.modules: munged[modpath] = mod for name, mod in munged.iteritems(): if name not in sys.modules: sys.modules[name] = mod if '.' in name: prename = name[:name.rfind('.')] postname = name[len(prename)+1:] if prename not in sys.modules: __import__(prename) if not hasattr(sys.modules[prename], postname): setattr(sys.modules[prename], postname, mod) return partdir, this_dir def __clone(): """ clone master version of autopath.py into all subdirs """ from os.path import join, walk if not this_dir.endswith(join('pypy','tool')): raise EnvironmentError("can only clone master version " "'%s'" % join(pypydir, 'tool',_myname)) def sync_walker(arg, dirname, fnames): if _myname in fnames: fn = join(dirname, _myname) f = open(fn, 'rwb+') try: if f.read() == arg: print "checkok", fn else: print "syncing", fn f = open(fn, 'w') f.write(arg) finally: f.close() s = open(join(pypydir, 'tool', _myname), 'rb').read() walk(pypydir, sync_walker, s) _myname = 'autopath.py' # set guaranteed attributes pypydir, this_dir = __dirinfo('pypy') if __name__ == '__main__': __clone()
Python
import autopath import py, os import sys from pypy.config.config import OptionDescription, BoolOption, IntOption, ArbitraryOption from pypy.config.config import ChoiceOption, StrOption, to_optparse, Config modulepath = py.magic.autopath().dirpath().dirpath().join("module") all_modules = [p.basename for p in modulepath.listdir() if p.check(dir=True, dotfile=False) and p.join('__init__.py').check()] essential_modules = dict.fromkeys( ["exceptions", "_file", "sys", "__builtin__", "posix"] ) default_modules = essential_modules.copy() default_modules.update(dict.fromkeys( ["_codecs", "gc", "_weakref", "array", "marshal", "errno", "math", "_sre", "_pickle_support", "operator", "recparser", "symbol", "_random", "__pypy__"])) working_modules = default_modules.copy() working_modules.update(dict.fromkeys( ["_socket", "unicodedata", "mmap", "fcntl", "rctime", "select", "crypt", "signal", "dyngram", "readline", "termios" ] )) if sys.platform == "win32": del working_modules["fcntl"] del working_modules["readline"] del working_modules["crypt"] module_dependencies = { } if os.name == "posix": module_dependencies['rctime'] = [("objspace.usemodules.select", True),] pypy_optiondescription = OptionDescription("objspace", "Object Space Options", [ ChoiceOption("name", "Object Space name", ["std", "flow", "logic", "thunk", "cpy", "dump", "taint"], "std", requires = { "logic": [#("objspace.geninterp", False), ("objspace.usemodules._stackless", True), ("objspace.usemodules._cslib", True), ("objspace.usemodules.cclp", True), ("translation.gc", 'framework'), ], }, cmdline='--objspace -o'), ChoiceOption("parser", "which parser to use for app-level code", ["pypy", "cpython"], "pypy", cmdline='--parser'), ChoiceOption("compiler", "which compiler to use for app-level code", ["cpython", "ast"], "ast", cmdline='--compiler'), OptionDescription("opcodes", "opcodes to enable in the interpreter", [ BoolOption("CALL_LIKELY_BUILTIN", "emit a special bytecode for likely calls to builtin functions", default=False, requires=[("objspace.std.withmultidict", True), ("translation.stackless", False)]), BoolOption("CALL_METHOD", "emit a special bytecode for expr.name()", default=False), ]), BoolOption("nofaking", "disallow faking in the object space", default=False, requires=[ ("objspace.usemodules.posix", True), ("objspace.usemodules.time", True), ("objspace.usemodules.errno", True)], cmdline='--nofaking'), OptionDescription("usemodules", "Which Modules should be used", [ BoolOption(modname, "use module %s" % (modname, ), default=modname in default_modules, cmdline="--withmod-%s" % (modname, ), requires=module_dependencies.get(modname, []), negation=modname not in essential_modules) for modname in all_modules]), BoolOption("allworkingmodules", "use as many working modules as possible", default=False, cmdline="--allworkingmodules", suggests=[("objspace.usemodules.%s" % (modname, ), True) for modname in working_modules if modname in all_modules], negation=False), BoolOption("geninterp", "specify whether geninterp should be used", cmdline=None, default=True), BoolOption("logbytecodes", "keep track of bytecode usage", default=False), BoolOption("usepycfiles", "Write and read pyc files when importing", default=True), BoolOption("honor__builtins__", "Honor the __builtins__ key of a module dictionary", default=False), OptionDescription("std", "Standard Object Space Options", [ BoolOption("withtproxy", "support transparent proxies", default=False), BoolOption("withsmallint", "use tagged integers", default=False, requires=[("translation.gc", "boehm")]), BoolOption("withprebuiltint", "prebuild commonly used int objects", default=False, requires=[("objspace.std.withsmallint", False)]), IntOption("prebuiltintfrom", "lowest integer which is prebuilt", default=-5, cmdline="--prebuiltintfrom"), IntOption("prebuiltintto", "highest integer which is prebuilt", default=100, cmdline="--prebuiltintto"), BoolOption("withstrjoin", "use strings optimized for addition", default=False), BoolOption("withstrslice", "use strings optimized for slicing", default=False), BoolOption("withprebuiltchar", "use prebuilt single-character string objects", default=False), BoolOption("sharesmallstr", "always reuse the prebuilt string objects " "(the empty string and potentially single-char strings)", default=False), BoolOption("withrope", "use ropes as the string implementation", default=False, requires=[("objspace.std.withstrslice", False), ("objspace.std.withstrjoin", False)], suggests=[("objspace.std.withprebuiltchar", True), ("objspace.std.sharesmallstr", True)]), BoolOption("withmultidict", "use dictionaries optimized for flexibility", default=False), BoolOption("withsharingdict", "use dictionaries that share the keys part", default=False, requires=[("objspace.std.withmultidict", True)]), BoolOption("withdictmeasurement", "create huge files with masses of information " "about dictionaries", default=False, requires=[("objspace.std.withmultidict", True)]), BoolOption("withbucketdict", "use dictionaries with chained hash tables " "(default is open addressing)", default=False, requires=[("objspace.std.withmultidict", True)]), BoolOption("withsmalldicts", "handle small dictionaries differently", default=False, requires=[("objspace.std.withmultidict", True)]), BoolOption("withrangelist", "enable special range list implementation that does not " "actually create the full list until the resulting " "list is mutated", default=False), BoolOption("withtypeversion", "version type objects when changing them", cmdline=None, default=False), BoolOption("withshadowtracking", "track whether an instance attribute shadows a type" " attribute", default=False, requires=[("objspace.std.withmultidict", True), ("objspace.std.withtypeversion", True)]), BoolOption("withmethodcache", "try to cache method lookups", default=False, requires=[("objspace.std.withtypeversion", True)]), BoolOption("withmethodcachecounter", "try to cache methods and provide a counter in __pypy__. " "for testing purposes only.", default=False, requires=[("objspace.std.withmethodcache", True)]), IntOption("methodcachesizeexp", " 2 ** methodcachesizeexp is the size of the of the method cache ", default=11), BoolOption("withmultilist", "use lists optimized for flexibility", default=False, requires=[("objspace.std.withrangelist", False), ("objspace.name", "std"), ("objspace.std.withtproxy", False)]), BoolOption("withfastslice", "make list slicing lazy", default=False, requires=[("objspace.std.withmultilist", True)]), BoolOption("withchunklist", "introducing a new nesting level to slow down list operations", default=False, requires=[("objspace.std.withmultilist", True)]), BoolOption("withsmartresizablelist", "only overallocate O(sqrt(n)) elements for lists", default=False, requires=[("objspace.std.withmultilist", True)]), BoolOption("optimized_int_add", "special case the addition of two integers in BINARY_ADD", default=False), BoolOption("optimized_list_getitem", "special case the 'list[integer]' expressions", default=False), BoolOption("oldstyle", "specify whether the default metaclass should be classobj", default=False, cmdline="--oldstyle"), BoolOption("logspaceoptypes", "a instrumentation option: before exit, print the types seen by " "certain simpler bytecodes", default=False), BoolOption("allopts", "enable all thought-to-be-working optimizations", default=False, suggests=[("objspace.opcodes.CALL_LIKELY_BUILTIN", True), ("objspace.opcodes.CALL_METHOD", True), ("translation.withsmallfuncsets", 5), ("translation.profopt", "-c 'from richards import main;main(); from test import pystone; pystone.main()'"), ("objspace.std.withmultidict", True), # ("objspace.std.withstrjoin", True), ("objspace.std.withshadowtracking", True), # ("objspace.std.withstrslice", True), # ("objspace.std.withsmallint", True), ("objspace.std.withrangelist", True), ("objspace.std.withmethodcache", True), # ("objspace.std.withfastslice", True), ("objspace.std.withprebuiltchar", True), # ("objspace.std.optimized_int_add", True), ], cmdline="--allopts --faassen", negation=False), ## BoolOption("llvmallopts", ## "enable all optimizations, and use llvm compiled via C", ## default=False, ## requires=[("objspace.std.allopts", True), ## ("translation.llvm_via_c", True), ## ("translation.backend", "llvm")], ## cmdline="--llvm-faassen", negation=False), ]), #BoolOption("lowmem", "Try to use less memory during translation", # default=False, cmdline="--lowmem", # requires=[("objspace.geninterp", False)]), ]) def get_pypy_config(overrides=None, translating=False): from pypy.config.translationoption import get_combined_translation_config return get_combined_translation_config( pypy_optiondescription, overrides=overrides, translating=translating) if __name__ == '__main__': config = get_pypy_config() print config.getpaths() parser = to_optparse(config) #, useoptions=["translation.*"]) option, args = parser.parse_args() print config
Python
import types, py from pypy.objspace.flow.model import Constant, FunctionGraph from pypy.interpreter.pycode import cpython_code_signature from pypy.interpreter.argument import rawshape from pypy.interpreter.argument import ArgErr from pypy.tool.sourcetools import valid_identifier from pypy.annotation.pairtype import extendabletype class CallFamily: """A family of Desc objects that could be called from common call sites. The call families are conceptually a partition of all (callable) Desc objects, where the equivalence relation is the transitive closure of 'd1~d2 if d1 and d2 might be called at the same call site'. """ overridden = False normalized = False def __init__(self, desc): self.descs = { desc: True } self.calltables = {} # see calltable_lookup_row() self.total_calltable_size = 0 def update(self, other): self.normalized = self.normalized or other.normalized self.descs.update(other.descs) for shape, table in other.calltables.items(): for row in table: self.calltable_add_row(shape, row) def calltable_lookup_row(self, callshape, row): # this code looks up a table of which graph to # call at which call site. Each call site gets a row of graphs, # sharable with other call sites. Each column is a FunctionDesc. # There is one such table per "call shape". table = self.calltables.setdefault(callshape, []) for i, existing_row in enumerate(table): if existing_row == row: # XXX maybe use a dict again here? return i raise LookupError def calltable_add_row(self, callshape, row): try: self.calltable_lookup_row(callshape, row) except LookupError: table = self.calltables.setdefault(callshape, []) table.append(row) self.total_calltable_size += 1 class FrozenAttrFamily: """A family of FrozenDesc objects that have any common 'getattr' sites. The attr families are conceptually a partition of FrozenDesc objects, where the equivalence relation is the transitive closure of: d1~d2 if d1 and d2 might have some attribute read on them by the same getattr operation. """ def __init__(self, desc): self.descs = {desc: True} self.read_locations = {} # set of position_keys self.attrs = {} # { attr: s_value } def update(self, other): self.descs.update(other.descs) self.read_locations.update(other.read_locations) self.attrs.update(other.attrs) def get_s_value(self, attrname): try: return self.attrs[attrname] except KeyError: from pypy.annotation.model import s_ImpossibleValue return s_ImpossibleValue def set_s_value(self, attrname, s_value): self.attrs[attrname] = s_value class ClassAttrFamily: """A family of ClassDesc objects that have common 'getattr' sites for a given attribute name. The attr families are conceptually a partition of ClassDesc objects, where the equivalence relation is the transitive closure of: d1~d2 if d1 and d2 might have a common attribute 'attrname' read on them by the same getattr operation. The 'attrname' is not explicitly stored here, but is the key used in the dictionary bookkeeper.pbc_maximal_access_sets_map. """ # The difference between ClassAttrFamily and FrozenAttrFamily is that # FrozenAttrFamily is the union for all attribute names, but # ClassAttrFamily is more precise: it is only about one attribut name. def __init__(self, desc): from pypy.annotation.model import s_ImpossibleValue self.descs = { desc: True } self.read_locations = {} # set of position_keys self.s_value = s_ImpossibleValue # union of possible values def update(self, other): from pypy.annotation.model import unionof self.descs.update(other.descs) self.read_locations.update(other.read_locations) self.s_value = unionof(self.s_value, other.s_value) def get_s_value(self, attrname): return self.s_value def set_s_value(self, attrname, s_value): self.s_value = s_value # ____________________________________________________________ class Desc(object): __metaclass__ = extendabletype def __init__(self, bookkeeper, pyobj=None): self.bookkeeper = bookkeeper # 'pyobj' is non-None if there is an associated underlying Python obj self.pyobj = pyobj def __repr__(self): pyobj = self.pyobj if pyobj is None: return object.__repr__(self) return '<%s for %r>' % (self.__class__.__name__, pyobj) def querycallfamily(self): """Retrieve the CallFamily object if there is one, otherwise return None.""" call_families = self.bookkeeper.pbc_maximal_call_families try: return call_families[self] except KeyError: return None def getcallfamily(self): """Get the CallFamily object. Possibly creates one.""" call_families = self.bookkeeper.pbc_maximal_call_families _, _, callfamily = call_families.find(self.rowkey()) return callfamily def mergecallfamilies(self, *others): """Merge the call families of the given Descs into one.""" call_families = self.bookkeeper.pbc_maximal_call_families changed, rep, callfamily = call_families.find(self.rowkey()) for desc in others: changed1, rep, callfamily = call_families.union(rep, desc.rowkey()) changed = changed or changed1 return changed def queryattrfamily(self): # no attributes supported by default; # overriden in FrozenDesc and ClassDesc return None def bind_under(self, classdef, name): return self def simplify_desc_set(descs): pass simplify_desc_set = staticmethod(simplify_desc_set) class NoStandardGraph(Exception): """The function doesn't have a single standard non-specialized graph.""" class FunctionDesc(Desc): knowntype = types.FunctionType overridden = False def __init__(self, bookkeeper, pyobj=None, name=None, signature=None, defaults=None, specializer=None): super(FunctionDesc, self).__init__(bookkeeper, pyobj) if name is None: name = pyobj.func_name if signature is None: signature = cpython_code_signature(pyobj.func_code) if defaults is None: defaults = pyobj.func_defaults self.name = name self.signature = signature self.defaults = defaults or () # 'specializer' is a function with the following signature: # specializer(funcdesc, args_s) => graph # or => s_result (overridden/memo cases) self.specializer = specializer self._cache = {} # convenience for the specializer def buildgraph(self, alt_name=None, builder=None): translator = self.bookkeeper.annotator.translator if builder: graph = builder(translator, self.pyobj) else: graph = translator.buildflowgraph(self.pyobj) if alt_name: graph.name = alt_name return graph def getuniquegraph(self): if len(self._cache) != 1: raise NoStandardGraph(self) [graph] = self._cache.values() if (graph.signature != self.signature or graph.defaults != self.defaults): raise NoStandardGraph(self) return graph def cachedgraph(self, key, alt_name=None, builder=None): try: return self._cache[key] except KeyError: def nameof(thing): if isinstance(thing, str): return thing elif hasattr(thing, '__name__'): # mostly types and functions return thing.__name__ elif hasattr(thing, 'name'): # mostly ClassDescs return thing.name elif isinstance(thing, tuple): return '_'.join(map(nameof, thing)) else: return str(thing)[:30] if key is not None and alt_name is None: postfix = valid_identifier(nameof(key)) alt_name = "%s__%s"%(self.name, postfix) graph = self.buildgraph(alt_name, builder) self._cache[key] = graph return graph def parse_arguments(self, args, graph=None): defs_s = [] if graph is None: signature = self.signature defaults = self.defaults else: signature = graph.signature defaults = graph.defaults if defaults: for x in defaults: defs_s.append(self.bookkeeper.immutablevalue(x)) try: inputcells = args.match_signature(signature, defs_s) except ArgErr, e: raise TypeError, "signature mismatch: %s" % e.getmsg(self.name) return inputcells def specialize(self, inputcells): if self.specializer is None: # get the specializer based on the tag of the 'pyobj' # (if any), according to the current policy tag = getattr(self.pyobj, '_annspecialcase_', None) policy = self.bookkeeper.annotator.policy self.specializer = policy.get_specializer(tag) enforceargs = getattr(self.pyobj, '_annenforceargs_', None) if enforceargs: if not callable(enforceargs): from pypy.annotation.policy import Sig enforceargs = Sig(*enforceargs) self.pyobj._annenforceargs_ = enforceargs enforceargs(self, inputcells) # can modify inputcells in-place return self.specializer(self, inputcells) def pycall(self, schedule, args, s_previous_result): inputcells = self.parse_arguments(args) result = self.specialize(inputcells) if isinstance(result, FunctionGraph): graph = result # common case # if that graph has a different signature, we need to re-parse # the arguments. # recreate the args object because inputcells may have been changed new_args = args.unmatch_signature(self.signature, inputcells) inputcells = self.parse_arguments(new_args, graph) result = schedule(graph, inputcells) # Some specializations may break the invariant of returning # annotations that are always more general than the previous time. # We restore it here: from pypy.annotation.model import unionof result = unionof(result, s_previous_result) return result def bind_under(self, classdef, name): # XXX static methods return self.bookkeeper.getmethoddesc(self, classdef, # originclassdef, None, # selfclassdef name) def consider_call_site(bookkeeper, family, descs, args, s_result): shape = rawshape(args) row = FunctionDesc.row_to_consider(descs, args) family.calltable_add_row(shape, row) consider_call_site = staticmethod(consider_call_site) def variant_for_call_site(bookkeeper, family, descs, args): shape = rawshape(args) bookkeeper.enter(None) try: row = FunctionDesc.row_to_consider(descs, args) finally: bookkeeper.leave() index = family.calltable_lookup_row(shape, row) return shape, index variant_for_call_site = staticmethod(variant_for_call_site) def rowkey(self): return self def row_to_consider(descs, args): # see comments in CallFamily from pypy.annotation.model import s_ImpossibleValue row = {} for desc in descs: def enlist(graph, ignore): row[desc.rowkey()] = graph return s_ImpossibleValue # meaningless desc.pycall(enlist, args, s_ImpossibleValue) return row row_to_consider = staticmethod(row_to_consider) def get_s_signatures(self, shape): family = self.getcallfamily() table = family.calltables.get(shape) if table is None: return [] else: graph_seen = {} s_sigs = [] binding = self.bookkeeper.annotator.binding def enlist(graph): if graph in graph_seen: return graph_seen[graph] = True s_sig = ([binding(v) for v in graph.getargs()], binding(graph.getreturnvar())) if s_sig in s_sigs: return s_sigs.append(s_sig) for row in table: for graph in row.itervalues(): enlist(graph) return s_sigs NODEFAULT = object() class ClassDesc(Desc): knowntype = type instance_level = False all_enforced_attrs = None # or a set settled = False def __init__(self, bookkeeper, pyobj=None, name=None, basedesc=None, classdict=None, specialize=None): super(ClassDesc, self).__init__(bookkeeper, pyobj) if name is None: name = pyobj.__module__ + '.' + pyobj.__name__ self.name = name self.basedesc = basedesc if classdict is None: classdict = {} # populated below self.classdict = classdict # {attr: Constant-or-Desc} if specialize is None: specialize = pyobj.__dict__.get('_annspecialcase_', '') self.specialize = specialize self._classdefs = {} if pyobj is not None: assert pyobj.__module__ != '__builtin__' cls = pyobj base = object baselist = list(cls.__bases__) baselist.reverse() # special case: skip BaseException in Python 2.5, and pretend # that all exceptions ultimately inherit from Exception instead # of BaseException (XXX hack) if cls is Exception: baselist = [] elif baselist == [py.builtin.BaseException]: baselist = [Exception] for b1 in baselist: if b1 is object: continue if b1.__dict__.get('_mixin_', False): assert b1.__bases__ == () or b1.__bases__ == (object,), ( "mixin class %r should have no base" % (b1,)) self.add_sources_for_class(b1, mixin=True) else: assert base is object, ("multiple inheritance only supported " "with _mixin_: %r" % (cls,)) base = b1 self.add_sources_for_class(cls) if base is not object: self.basedesc = bookkeeper.getdesc(base) if '_settled_' in cls.__dict__: self.settled = bool(cls.__dict__['_settled_']) if '__slots__' in cls.__dict__ or '_attrs_' in cls.__dict__: attrs = {} for decl in ('__slots__', '_attrs_'): decl = cls.__dict__.get(decl, []) if isinstance(decl, str): decl = (decl,) decl = dict.fromkeys(decl) attrs.update(decl) if self.basedesc is not None: if self.basedesc.all_enforced_attrs is None: raise Exception("%r has slots or _attrs_, " "but not its base class" % (pyobj,)) attrs.update(self.basedesc.all_enforced_attrs) self.all_enforced_attrs = attrs def add_source_attribute(self, name, value, mixin=False): if isinstance(value, types.FunctionType): # for debugging if not hasattr(value, 'class_'): value.class_ = self.pyobj # remember that this is really a method if self.specialize: # make a custom funcdesc that specializes on its first # argument (i.e. 'self'). from pypy.annotation.specialize import specialize_argtype def argtype0(funcdesc, args_s): return specialize_argtype(funcdesc, args_s, 0) funcdesc = FunctionDesc(self.bookkeeper, value, specializer=argtype0) self.classdict[name] = funcdesc return if mixin: # make a new copy of the FunctionDesc for this class, # but don't specialize further for all subclasses funcdesc = FunctionDesc(self.bookkeeper, value) self.classdict[name] = funcdesc return # NB. if value is, say, AssertionError.__init__, then we # should not use getdesc() on it. Never. The problem is # that the py lib has its own AssertionError.__init__ which # is of type FunctionType. But bookkeeper.immutablevalue() # will do the right thing in s_get_value(). if type(value) is MemberDescriptorType: # skip __slots__, showing up in the class as 'member' objects return if name == '__init__' and self.is_builtin_exception_class(): # pretend that built-in exceptions have no __init__, # unless explicitly specified in builtin.py from pypy.annotation.builtin import BUILTIN_ANALYZERS value = getattr(value, 'im_func', value) if value not in BUILTIN_ANALYZERS: return self.classdict[name] = Constant(value) def add_sources_for_class(self, cls, mixin=False): for name, value in cls.__dict__.items(): self.add_source_attribute(name, value, mixin) def getclassdef(self, key): try: return self._classdefs[key] except KeyError: from pypy.annotation.classdef import ClassDef, FORCE_ATTRIBUTES_INTO_CLASSES classdef = ClassDef(self.bookkeeper, self) self.bookkeeper.classdefs.append(classdef) self._classdefs[key] = classdef # forced attributes if self.pyobj is not None: cls = self.pyobj if cls in FORCE_ATTRIBUTES_INTO_CLASSES: for name, s_value in FORCE_ATTRIBUTES_INTO_CLASSES[cls].items(): classdef.generalize_attr(name, s_value) classdef.find_attribute(name).modified(classdef) # register all class attributes as coming from this ClassDesc # (as opposed to prebuilt instances) classsources = {} for attr in self.classdict: classsources[attr] = self # comes from this ClassDesc classdef.setup(classsources) # look for a __del__ method and annotate it if it's there if '__del__' in self.classdict: from pypy.annotation.model import s_None, SomeInstance s_func = self.s_read_attribute('__del__') args_s = [SomeInstance(classdef)] s = self.bookkeeper.emulate_pbc_call(classdef, s_func, args_s) assert s_None.contains(s) return classdef def getuniqueclassdef(self): if self.specialize: raise Exception("not supported on class %r because it needs " "specialization" % (self.name,)) return self.getclassdef(None) def pycall(self, schedule, args, s_previous_result): from pypy.annotation.model import SomeInstance, SomeImpossibleValue if self.specialize: if self.specialize == 'specialize:ctr_location': # We use the SomeInstance annotation returned the last time # to make sure we use the same ClassDef this time. if isinstance(s_previous_result, SomeInstance): classdef = s_previous_result.classdef else: classdef = self.getclassdef(object()) else: raise Exception("unsupported specialization tag: %r" % ( self.specialize,)) else: classdef = self.getuniqueclassdef() s_instance = SomeInstance(classdef) # look up __init__ directly on the class, bypassing the normal # lookup mechanisms ClassDef (to avoid influencing Attribute placement) s_init = self.s_read_attribute('__init__') if isinstance(s_init, SomeImpossibleValue): # no __init__: check that there are no constructor args if not self.is_exception_class(): try: args.fixedunpack(0) except ValueError: raise Exception("default __init__ takes no argument" " (class %s)" % (self.name,)) else: # call the constructor args = args.prepend(s_instance) s_init.call(args) return s_instance def is_exception_class(self): return self.pyobj is not None and issubclass(self.pyobj, py.builtin.BaseException) def is_builtin_exception_class(self): if self.is_exception_class(): if self.pyobj.__module__ == 'exceptions': return True if self.pyobj is py.magic.AssertionError: return True return False def lookup(self, name): cdesc = self while name not in cdesc.classdict: cdesc = cdesc.basedesc if cdesc is None: return None else: return cdesc def read_attribute(self, name, default=NODEFAULT): cdesc = self.lookup(name) if cdesc is None: if default is NODEFAULT: raise AttributeError else: return default else: return cdesc.classdict[name] def s_read_attribute(self, name): # look up an attribute in the class cdesc = self.lookup(name) if cdesc is None: from pypy.annotation.model import s_ImpossibleValue return s_ImpossibleValue else: # delegate to s_get_value to turn it into an annotation return cdesc.s_get_value(None, name) def s_get_value(self, classdef, name): obj = self.classdict[name] if isinstance(obj, Constant): value = obj.value if isinstance(value, staticmethod): # special case value = value.__get__(42) classdef = None # don't bind s_value = self.bookkeeper.immutablevalue(value) if classdef is not None: s_value = s_value.bind_callables_under(classdef, name) elif isinstance(obj, Desc): from pypy.annotation.model import SomePBC if classdef is not None: obj = obj.bind_under(classdef, name) s_value = SomePBC([obj]) else: raise TypeError("classdict should not contain %r" % (obj,)) return s_value def create_new_attribute(self, name, value): assert name not in self.classdict, "name clash: %r" % (name,) self.classdict[name] = Constant(value) def find_source_for(self, name): if name in self.classdict: return self if self.pyobj is not None: # check whether in the case the classdesc corresponds to a real class # there is a new attribute cls = self.pyobj if name in cls.__dict__: self.add_source_attribute(name, cls.__dict__[name]) if name in self.classdict: return self return None def consider_call_site(bookkeeper, family, descs, args, s_result): from pypy.annotation.model import SomeInstance, SomePBC, s_None if len(descs) == 1: # call to a single class, look at the result annotation # in case it was specialized if not isinstance(s_result, SomeInstance): raise Exception("calling a class didn't return an instance??") classdefs = [s_result.classdef] else: # call to multiple classes: specialization not supported classdefs = [desc.getuniqueclassdef() for desc in descs] # make a PBC of MethodDescs, one for the __init__ of each class initdescs = [] for desc, classdef in zip(descs, classdefs): s_init = desc.s_read_attribute('__init__') if isinstance(s_init, SomePBC): assert len(s_init.descriptions) == 1, ( "unexpected dynamic __init__?") initfuncdesc = s_init.descriptions.keys()[0] if isinstance(initfuncdesc, FunctionDesc): initmethdesc = bookkeeper.getmethoddesc(initfuncdesc, classdef, classdef, '__init__') initdescs.append(initmethdesc) # register a call to exactly these __init__ methods if initdescs: initdescs[0].mergecallfamilies(*initdescs[1:]) initfamily = initdescs[0].getcallfamily() MethodDesc.consider_call_site(bookkeeper, initfamily, initdescs, args, s_None) consider_call_site = staticmethod(consider_call_site) def rowkey(self): return self def getattrfamily(self, attrname): "Get the ClassAttrFamily object for attrname. Possibly creates one." access_sets = self.bookkeeper.get_classpbc_attr_families(attrname) _, _, attrfamily = access_sets.find(self) return attrfamily def queryattrfamily(self, attrname): """Retrieve the ClassAttrFamily object for attrname if there is one, otherwise return None.""" access_sets = self.bookkeeper.get_classpbc_attr_families(attrname) try: return access_sets[self] except KeyError: return None def mergeattrfamilies(self, others, attrname): """Merge the attr families of the given Descs into one.""" access_sets = self.bookkeeper.get_classpbc_attr_families(attrname) changed, rep, attrfamily = access_sets.find(self) for desc in others: changed1, rep, attrfamily = access_sets.union(rep, desc) changed = changed or changed1 return changed class MethodDesc(Desc): knowntype = types.MethodType def __init__(self, bookkeeper, funcdesc, originclassdef, selfclassdef, name, flags={}): super(MethodDesc, self).__init__(bookkeeper) self.funcdesc = funcdesc self.originclassdef = originclassdef self.selfclassdef = selfclassdef self.name = name self.flags = flags def __repr__(self): if self.selfclassdef is None: return '<unbound MethodDesc %r of %r>' % (self.name, self.originclassdef) else: return '<MethodDesc %r of %r bound to %r %r>' % (self.name, self.originclassdef, self.selfclassdef, self.flags) def pycall(self, schedule, args, s_previous_result): from pypy.annotation.model import SomeInstance if self.selfclassdef is None: raise Exception("calling %r" % (self,)) s_instance = SomeInstance(self.selfclassdef, flags = self.flags) args = args.prepend(s_instance) return self.funcdesc.pycall(schedule, args, s_previous_result) def bind_under(self, classdef, name): self.bookkeeper.warning("rebinding an already bound %r" % (self,)) return self.funcdesc.bind_under(classdef, name) def bind_self(self, newselfclassdef, flags={}): return self.bookkeeper.getmethoddesc(self.funcdesc, self.originclassdef, newselfclassdef, self.name, flags) def consider_call_site(bookkeeper, family, descs, args, s_result): shape = rawshape(args, nextra=1) # account for the extra 'self' funcdescs = [methoddesc.funcdesc for methoddesc in descs] row = FunctionDesc.row_to_consider(descs, args) family.calltable_add_row(shape, row) consider_call_site = staticmethod(consider_call_site) def rowkey(self): # we are computing call families and call tables that always contain # FunctionDescs, not MethodDescs. The present method returns the # FunctionDesc to use as a key in that family. return self.funcdesc def simplify_desc_set(descs): # Some hacking needed to make contains() happy on SomePBC: if the # set of MethodDescs contains some "redundant" ones, i.e. ones that # are less general than others already in the set, then kill them. # This ensures that if 'a' is less general than 'b', then # SomePBC({a}) union SomePBC({b}) is again SomePBC({b}). # # Two cases: # 1. if two MethodDescs differ in their selfclassdefs, and if one # of the selfclassdefs is a subclass of the other; # 2. if two MethodDescs differ in their flags, take the intersection. # --- case 2 --- # only keep the intersection of all the flags, that's good enough lst = list(descs) commonflags = lst[0].flags.copy() for key, value in commonflags.items(): for desc in lst[1:]: if key not in desc.flags or desc.flags[key] != value: del commonflags[key] break for desc in lst: if desc.flags != commonflags: newdesc = desc.bookkeeper.getmethoddesc(desc.funcdesc, desc.originclassdef, desc.selfclassdef, desc.name, commonflags) del descs[desc] descs[newdesc] = None # --- case 1 --- groups = {} for desc in descs: if desc.selfclassdef is not None: key = desc.funcdesc, desc.originclassdef, desc.name groups.setdefault(key, []).append(desc) for group in groups.values(): if len(group) > 1: for desc1 in group: cdef1 = desc1.selfclassdef for desc2 in group: cdef2 = desc2.selfclassdef if cdef1 is not cdef2 and cdef1.issubclass(cdef2): del descs[desc1] break simplify_desc_set = staticmethod(simplify_desc_set) def new_or_old_class(c): if hasattr(c, '__class__'): return c.__class__ else: return type(c) class FrozenDesc(Desc): def __init__(self, bookkeeper, pyobj, read_attribute=None): super(FrozenDesc, self).__init__(bookkeeper, pyobj) if read_attribute is None: read_attribute = lambda attr: getattr(pyobj, attr) self._read_attribute = read_attribute self.attrcache = {} self.knowntype = new_or_old_class(pyobj) assert bool(pyobj), "__nonzero__ unsupported on frozen PBC %r" %(pyobj,) def read_attribute(self, attr): try: return self.attrcache[attr] except KeyError: result = self.attrcache[attr] = self._read_attribute(attr) return result def s_read_attribute(self, attr): try: value = self.read_attribute(attr) except AttributeError: from pypy.annotation.model import s_ImpossibleValue return s_ImpossibleValue else: return self.bookkeeper.immutablevalue(value) def create_new_attribute(self, name, value): try: self.read_attribute(name) except AttributeError: pass else: raise AssertionError("name clash: %r" % (name,)) self.attrcache[name] = value def getattrfamily(self, attrname=None): "Get the FrozenAttrFamily object for attrname. Possibly creates one." access_sets = self.bookkeeper.frozenpbc_attr_families _, _, attrfamily = access_sets.find(self) return attrfamily def queryattrfamily(self, attrname=None): """Retrieve the FrozenAttrFamily object for attrname if there is one, otherwise return None.""" access_sets = self.bookkeeper.frozenpbc_attr_families try: return access_sets[self] except KeyError: return None def mergeattrfamilies(self, others, attrname=None): """Merge the attr families of the given Descs into one.""" access_sets = self.bookkeeper.frozenpbc_attr_families changed, rep, attrfamily = access_sets.find(self) for desc in others: changed1, rep, attrfamily = access_sets.union(rep, desc) changed = changed or changed1 return changed class MethodOfFrozenDesc(Desc): knowntype = types.MethodType def __init__(self, bookkeeper, funcdesc, frozendesc): super(MethodOfFrozenDesc, self).__init__(bookkeeper) self.funcdesc = funcdesc self.frozendesc = frozendesc def __repr__(self): return '<MethodOfFrozenDesc %r of %r>' % (self.funcdesc, self.frozendesc) def pycall(self, schedule, args, s_previous_result): from pypy.annotation.model import SomePBC s_self = SomePBC([self.frozendesc]) args = args.prepend(s_self) return self.funcdesc.pycall(schedule, args, s_previous_result) def consider_call_site(bookkeeper, family, descs, args, s_result): shape = rawshape(args, nextra=1) # account for the extra 'self' funcdescs = [mofdesc.funcdesc for mofdesc in descs] row = FunctionDesc.row_to_consider(descs, args) family.calltable_add_row(shape, row) consider_call_site = staticmethod(consider_call_site) def rowkey(self): return self.funcdesc # ____________________________________________________________ class Sample(object): __slots__ = 'x' MemberDescriptorType = type(Sample.x) del Sample
Python
# specialization support import types import py from pypy.tool.uid import uid from pypy.tool.sourcetools import func_with_new_name from pypy.tool.algo.unionfind import UnionFind from pypy.objspace.flow.model import Block, Link, Variable, SpaceOperation from pypy.objspace.flow.model import Constant, checkgraph from pypy.annotation import model as annmodel def default_specialize(funcdesc, args_s): argnames, vararg, kwarg = funcdesc.signature assert not kwarg, "functions with ** arguments are not supported" if vararg: # calls to *arg functions: create one version per number of args assert len(args_s) == len(argnames) + 1 s_tuple = args_s[-1] assert isinstance(s_tuple, annmodel.SomeTuple), ( "calls f(..., *arg) require 'arg' to be a tuple") s_len = s_tuple.len() assert s_len.is_constant(), "calls require known number of args" nb_extra_args = s_len.const flattened_s = list(args_s[:-1]) flattened_s.extend(s_tuple.items) def builder(translator, func): # build a hacked graph that doesn't take a *arg any more, but # individual extra arguments graph = translator.buildflowgraph(func) argnames, vararg, kwarg = graph.signature assert vararg, "graph should have a *arg at this point" assert not kwarg, "where does this **arg come from??" argscopy = [Variable(v) for v in graph.getargs()] starargs = [Variable('stararg%d'%i) for i in range(nb_extra_args)] newstartblock = Block(argscopy[:-1] + starargs) newtup = SpaceOperation('newtuple', starargs, argscopy[-1]) newstartblock.operations.append(newtup) newstartblock.closeblock(Link(argscopy, graph.startblock)) graph.startblock.isstartblock = False graph.startblock = newstartblock newstartblock.isstartblock = True argnames += tuple(['.star%d' % i for i in range(nb_extra_args)]) graph.signature = argnames, None, None # note that we can mostly ignore defaults: if nb_extra_args > 0, # then defaults aren't applied. if nb_extra_args == 0, then this # just removes the *arg and the defaults keep their meaning. if nb_extra_args > 0: graph.defaults = None # shouldn't be used in this case checkgraph(graph) return graph key, name_suffix = access_direct_key(nb_extra_args, flattened_s) return funcdesc.cachedgraph(key, alt_name='%s_star%d%s' % (funcdesc.name, nb_extra_args, name_suffix), builder=builder) else: key, name_suffix = access_direct_key(None, args_s) if name_suffix: alt_name = '%s%s' % (funcdesc.name, name_suffix) else: alt_name = None return funcdesc.cachedgraph(key, alt_name=alt_name) def access_direct_key(key, args_s): for s_obj in args_s: if (isinstance(s_obj, annmodel.SomeInstance) and 'access_directly' in s_obj.flags): return (AccessDirect, key), '_AccessDirect' return key, '' class AccessDirect(object): """marker for specialization: set when any arguments is a SomeInstance which has the 'access_directly' flag set.""" def getuniquenondirectgraph(desc): result = [] for key, graph in desc._cache.items(): if (type(key) is tuple and len(key) == 2 and key[0] is AccessDirect): continue result.append(graph) assert len(result) == 1 return result[0] # ____________________________________________________________________________ # specializations class MemoTable: def __init__(self, funcdesc, args, value): self.funcdesc = funcdesc self.table = {args: value} self.graph = None def update(self, other): self.table.update(other.table) self.graph = None # just in case fieldnamecounter = 0 def getuniquefieldname(self): name = self.funcdesc.name fieldname = '$memofield_%s_%d' % (name, MemoTable.fieldnamecounter) MemoTable.fieldnamecounter += 1 return fieldname def finish(self): from pypy.annotation.model import unionof assert self.graph is None, "MemoTable already finished" # list of which argument positions can take more than one value example_args, example_value = self.table.iteritems().next() nbargs = len(example_args) # list of sets of possible argument values -- one set per argument index sets = [{} for i in range(nbargs)] for args in self.table: for i in range(nbargs): sets[i][args[i]] = True bookkeeper = self.funcdesc.bookkeeper annotator = bookkeeper.annotator name = self.funcdesc.name argnames = ['a%d' % i for i in range(nbargs)] def make_helper(firstarg, stmt, miniglobals): header = "def f(%s):" % (', '.join(argnames[firstarg:],)) source = py.code.Source(stmt) source = source.putaround(header) exec source.compile() in miniglobals f = miniglobals['f'] return func_with_new_name(f, 'memo_%s_%d' % (name, firstarg)) def make_constant_subhelper(firstarg, result): # make a function that just returns the constant answer 'result' f = make_helper(firstarg, 'return result', {'result': result}) f.constant_result = result return f def make_subhelper(args_so_far=()): firstarg = len(args_so_far) if firstarg == nbargs: # no argument left, return the known result # (or a dummy value if none corresponds exactly) result = self.table.get(args_so_far, example_value) return make_constant_subhelper(firstarg, result) else: nextargvalues = list(sets[len(args_so_far)]) if nextargvalues == [True, False]: nextargvalues = [False, True] nextfns = [make_subhelper(args_so_far + (arg,)) for arg in nextargvalues] # do all graphs return a constant? try: constants = [fn.constant_result for fn in nextfns] except AttributeError: constants = None # one of the 'fn' has no constant_result restargs = ', '.join(argnames[firstarg+1:]) # is there actually only one possible value for the current arg? if len(nextargvalues) == 1: if constants: # is the result a constant? result = constants[0] return make_constant_subhelper(firstarg, result) else: # ignore the first argument and just call the subhelper stmt = 'return subhelper(%s)' % restargs return make_helper(firstarg, stmt, {'subhelper': nextfns[0]}) # is the arg a bool? elif nextargvalues == [False, True]: fieldname0 = self.getuniquefieldname() fieldname1 = self.getuniquefieldname() stmt = ['if %s:' % argnames[firstarg]] if hasattr(nextfns[True], 'constant_result'): # the True branch has a constant result case1 = nextfns[True].constant_result stmt.append(' return case1') else: # must call the subhelper case1 = nextfns[True] stmt.append(' return case1(%s)' % restargs) stmt.append('else:') if hasattr(nextfns[False], 'constant_result'): # the False branch has a constant result case0 = nextfns[False].constant_result stmt.append(' return case0') else: # must call the subhelper case0 = nextfns[False] stmt.append(' return case0(%s)' % restargs) return make_helper(firstarg, '\n'.join(stmt), {'case0': case0, 'case1': case1}) # the arg is a set of PBCs else: descs = [bookkeeper.getdesc(pbc) for pbc in nextargvalues] fieldname = self.getuniquefieldname() stmt = 'return getattr(%s, %r)' % (argnames[firstarg], fieldname) if constants: # instead of calling these subhelpers indirectly, # we store what they would return directly in the # pbc memo fields store = constants else: store = nextfns # call the result of the getattr() stmt += '(%s)' % restargs # store the memo field values for desc, value_to_store in zip(descs, store): desc.create_new_attribute(fieldname, value_to_store) return make_helper(firstarg, stmt, {}) entrypoint = make_subhelper(args_so_far = ()) self.graph = annotator.translator.buildflowgraph(entrypoint) # schedule this new graph for being annotated args_s = [] for set in sets: values_s = [bookkeeper.immutablevalue(x) for x in set] args_s.append(unionof(*values_s)) annotator.addpendinggraph(self.graph, args_s) def memo(funcdesc, arglist_s): from pypy.annotation.model import SomePBC, SomeImpossibleValue, SomeBool from pypy.annotation.model import unionof # call the function now, and collect possible results argvalues = [] for s in arglist_s: if s.is_constant(): values = [s.const] elif isinstance(s, SomePBC): values = [] assert not s.can_be_None, "memo call: cannot mix None and PBCs" for desc in s.descriptions: if desc.pyobj is None: raise Exception("memo call with a class or PBC that has no " "corresponding Python object (%r)" % (desc,)) values.append(desc.pyobj) elif isinstance(s, SomeImpossibleValue): return s # we will probably get more possible args later elif isinstance(s, SomeBool): values = [False, True] else: raise Exception("memo call: argument must be a class or a frozen " "PBC, got %r" % (s,)) argvalues.append(values) # the list of all possible tuples of arguments to give to the memo function possiblevalues = cartesian_product(argvalues) # a MemoTable factory -- one MemoTable per family of arguments that can # be called together, merged via a UnionFind. bookkeeper = funcdesc.bookkeeper try: memotables = bookkeeper.all_specializations[funcdesc] except KeyError: func = funcdesc.pyobj if func is None: raise Exception("memo call: no Python function object to call " "(%r)" % (funcdesc,)) def compute_one_result(args): value = func(*args) memotable = MemoTable(funcdesc, args, value) bookkeeper.pending_specializations.append(memotable.finish) return memotable memotables = UnionFind(compute_one_result) bookkeeper.all_specializations[funcdesc] = memotables # merge the MemoTables for the individual argument combinations firstvalues = possiblevalues.next() _, _, memotable = memotables.find(firstvalues) for values in possiblevalues: _, _, memotable = memotables.union(firstvalues, values) if memotable.graph is not None: return memotable.graph # if already computed else: # otherwise, for now, return the union of each possible result return unionof(*[bookkeeper.immutablevalue(v) for v in memotable.table.values()]) def cartesian_product(lstlst): if not lstlst: yield () return for tuple_tail in cartesian_product(lstlst[1:]): for value in lstlst[0]: yield (value,) + tuple_tail ## """NOT_RPYTHON""" ## if len(arglist_s) != 1: ## raise Exception("memo call: only 1 argument functions supported" ## " at the moment (%r)" % (funcdesc,)) ## s, = arglist_s ## from pypy.annotation.model import SomeImpossibleValue ## return memo1(funcdesc, func, s) ### XXX OBSCURE to support methodmemo()... needs to find something more ### reasonable :-( ##KEY_NUMBERS = {} ##def memo1(funcdesc, func, s, key='memo1'): ## from pypy.annotation.model import SomeImpossibleValue ## # compute the concrete results and store them directly on the descs, ## # using a strange attribute name ## num = KEY_NUMBERS.setdefault(key, len(KEY_NUMBERS)) ## attrname = '$memo%d_%d_%s' % (uid(funcdesc), num, funcdesc.name) ## for desc in s.descriptions: ## s_result = desc.s_read_attribute(attrname) ## if isinstance(s_result, SomeImpossibleValue): ## # first time we see this 'desc' ## if desc.pyobj is None: ## raise Exception("memo call with a class or PBC that has no " ## "corresponding Python object (%r)" % (desc,)) ## result = func(desc.pyobj) ## desc.create_new_attribute(attrname, result) ## # get or build the graph of the function that reads this strange attr ## def memoized(x, y=None): ## return getattr(x, attrname) ## def builder(translator, func): ## return translator.buildflowgraph(memoized) # instead of 'func' ## return funcdesc.cachedgraph(key, alt_name='memo_%s' % funcdesc.name, ## builder=builder) ##def methodmemo(funcdesc, arglist_s): ## """NOT_RPYTHON""" ## from pypy.annotation.model import SomePBC, SomeImpossibleValue ## # call the function now, and collect possible results ## for s in arglist_s: ## if not isinstance(s, SomePBC): ## if isinstance(s, SomeImpossibleValue): ## return s # we will probably get more possible args later ## raise Exception("method-memo call: argument must be a class or" ## " a frozen PBC, got %r" % (s,)) ## if len(arglist_s) != 2: ## raise Exception("method-memo call: expected 2 arguments function" ## " at the moment (%r)" % (funcdesc,)) ## from pypy.annotation.model import SomeImpossibleValue ## from pypy.annotation.description import FrozenDesc ## func = funcdesc.pyobj ## if func is None: ## raise Exception("method-memo call: no Python function object to call" ## " (%r)" % (funcdesc,)) ## # compute the concrete results and store them directly on the descs, ## # using a strange attribute name. The goal is to store in the pbcs of ## # 's1' under the common 'attrname' a reader function; each reader function ## # will read a field 'attrname2' from the pbcs of 's2', where 'attrname2' ## # differs for each pbc of 's1'. This is all specialized also ## # considering the type of s1 to support return value ## # polymorphism. ## s1, s2 = arglist_s ## s1_type = s1.knowntype ## if s2.is_constant(): ## return memo1(funcdesc, lambda val1: func(val1, s2.const), ## s1, ('memo1of2', s1_type, Constant(s2.const))) ## memosig = "%d_%d_%s" % (uid(funcdesc), uid(s1_type), funcdesc.name) ## attrname = '$memoreader%s' % memosig ## for desc1 in s1.descriptions: ## attrname2 = '$memofield%d_%s' % (uid(desc1), memosig) ## s_reader = desc1.s_read_attribute(attrname) ## if isinstance(s_reader, SomeImpossibleValue): ## # first time we see this 'desc1': sanity-check 'desc1' and ## # create its reader function ## assert isinstance(desc1, FrozenDesc), ( ## "XXX not implemented: memo call with a class as first arg") ## if desc1.pyobj is None: ## raise Exception("method-memo call with a class or PBC" ## " that has no " ## "corresponding Python object (%r)" % (desc1,)) ## def reader(y, attrname2=attrname2): ## return getattr(y, attrname2) ## desc1.create_new_attribute(attrname, reader) ## for desc2 in s2.descriptions: ## s_result = desc2.s_read_attribute(attrname2) ## if isinstance(s_result, SomeImpossibleValue): ## # first time we see this 'desc1+desc2' combination ## if desc2.pyobj is None: ## raise Exception("method-memo call with a class or PBC" ## " that has no " ## "corresponding Python object (%r)" % (desc2,)) ## # concrete call, to get the concrete result ## result = func(desc1.pyobj, desc2.pyobj) ## #print 'func(%s, %s) -> %s' % (desc1.pyobj, desc2.pyobj, result) ## #print 'goes into %s.%s'% (desc2,attrname2) ## #print 'with reader %s.%s'% (desc1,attrname) ## desc2.create_new_attribute(attrname2, result) ## # get or build the graph of the function that reads this indirect ## # settings of attributes ## def memoized(x, y): ## reader_fn = getattr(x, attrname) ## return reader_fn(y) ## def builder(translator, func): ## return translator.buildflowgraph(memoized) # instead of 'func' ## return funcdesc.cachedgraph(s1_type, alt_name='memo_%s' % funcdesc.name, ## builder=builder) def make_constgraphbuilder(n, v=None, factory=None): def constgraphbuilder(translator, ignore): args = ','.join(["arg%d" % i for i in range(n)]) if factory is not None: computed_v = factory() else: computed_v = v miniglobals = {'v': computed_v} exec "constf = lambda %s: v" % args in miniglobals return translator.buildflowgraph(miniglobals['constf']) return constgraphbuilder def specialize_argvalue(funcdesc, args_s, *argindices): key = tuple([args_s[i].const for i in argindices]) return funcdesc.cachedgraph(key) def specialize_argtype(funcdesc, args_s, *argindices): key = tuple([args_s[i].knowntype for i in argindices]) return funcdesc.cachedgraph(key) def specialize_arglistitemtype(funcdesc, args_s, i): s = args_s[i] if s.knowntype is not list: key = None else: key = s.listdef.listitem.s_value.knowntype return funcdesc.cachedgraph(key)
Python