[Python-checkins] r79077 - sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py

benjamin.peterson python-checkins at python.org
Fri Mar 19 00:05:29 CET 2010


Author: benjamin.peterson
Date: Fri Mar 19 00:05:29 2010
New Revision: 79077

Log:
port detect_encoding improvements from py3k

Modified:
   sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py

Modified: sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py
==============================================================================
--- sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py	(original)
+++ sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py	Fri Mar 19 00:05:29 2010
@@ -251,14 +251,16 @@
     in.
 
     It detects the encoding from the presence of a utf-8 bom or an encoding
-    cookie as specified in pep-0263. If both a bom and a cookie are present,
-    but disagree, a SyntaxError will be raised. If the encoding cookie is an
-    invalid charset, raise a SyntaxError.
+    cookie as specified in pep-0263. If both a bom and a cookie are present, but
+    disagree, a SyntaxError will be raised. If the encoding cookie is an invalid
+    charset, raise a SyntaxError.  Note that if a utf-8 bom is found,
+    'utf-8-sig' is returned.
 
     If no encoding is specified, then the default of 'utf-8' will be returned.
     """
     bom_found = False
     encoding = None
+    default = 'utf-8'
     def read_or_stop():
         try:
             return readline()
@@ -285,17 +287,16 @@
             if codec.name != 'utf-8':
                 # This behaviour mimics the Python interpreter
                 raise SyntaxError('encoding problem: utf-8')
-            else:
-                # Allow it to be properly encoded and decoded.
-                encoding = 'utf-8-sig'
+            encoding += '-sig'
         return encoding
 
     first = read_or_stop()
     if first.startswith(BOM_UTF8):
         bom_found = True
         first = first[3:]
+        default = 'utf-8-sig'
     if not first:
-        return 'utf-8', []
+        return default, []
 
     encoding = find_cookie(first)
     if encoding:
@@ -303,13 +304,13 @@
 
     second = read_or_stop()
     if not second:
-        return 'utf-8', [first]
+        return default, [first]
 
     encoding = find_cookie(second)
     if encoding:
         return encoding, [first, second]
 
-    return 'utf-8', [first, second]
+    return default, [first, second]
 
 def untokenize(iterable):
     """Transform tokens back into Python source code.


More information about the Python-checkins mailing list