FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

reuse tokenize.detect_encoding in linecache instead of a custom solution · python/cpython@9b8d24b · GitHub

Repository navigation

Commit 9b8d24b

Browse files
committed
reuse tokenize.detect_encoding in linecache instead of a custom solution
patch by Victor Stinner #4016
1 parent a8abe86 commit 9b8d24b

2 files changed

Lines changed: 8 additions & 23 deletions

File tree

‎Lib/linecache.py‎

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import sys
99
import os
10-
import re
10+
import tokenize
1111

1212
__all__ = ["getline", "clearcache", "checkcache"]
1313

@@ -120,27 +120,11 @@ def updatecache(filename, module_globals=None):
120120
pass
121121
else:
122122
# No luck
123-
## print '*** Cannot stat', filename, ':', msg
124123
return []
125-
## print("Refreshing cache for %s..." % fullname)
126-
try:
127-
fp = open(fullname, 'rU')
124+
with open(fullname, 'rb') as fp:
125+
coding, line = tokenize.detect_encoding(fp.readline)
126+
with open(fullname, 'r', encoding=coding) as fp:
128127
lines = fp.readlines()
129-
fp.close()
130-
except Exception as msg:
131-
## print '*** Cannot open', fullname, ':', msg
132-
return []
133-
coding = "utf-8"
134-
for line in lines[:2]:
135-
m = re.search(r"coding[:=]\s*([-\w.]+)", line)
136-
if m:
137-
coding = m.group(1)
138-
break
139-
try:
140-
lines = [line if isinstance(line, str) else str(line, coding)
141-
for line in lines]
142-
except:
143-
pass # Hope for the best
144128
size, mtime = stat.st_size, stat.st_mtime
145129
cache[filename] = size, mtime, lines, fullname
146130
return lines

‎Lib/tokenize.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
import re, string, sys
2828
from token import *
2929
from codecs import lookup, BOM_UTF8
30-
from itertools import chain, repeat
3130
cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
3231

3332
import token
@@ -327,13 +326,15 @@ def tokenize(readline):
327326
which tells you which encoding was used to decode the bytes stream.
328327
"""
329328
encoding, consumed = detect_encoding(readline)
330-
def readline_generator():
329+
def readline_generator(consumed):
330+
for line in consumed:
331+
yield line
331332
while True:
332333
try:
333334
yield readline()
334335
except StopIteration:
335336
return
336-
chained = chain(consumed, readline_generator())
337+
chained = readline_generator(consumed)
337338
return _tokenize(chained.__next__, encoding)
338339

339340

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL