Commit 96917509 authored by Victor Stinner's avatar Victor Stinner

Issue #22599: Enhance tokenize.open() to be able to call it during Python

finalization.

Before the module kept a reference to the builtins module, but the module
attributes are cleared during Python finalization. Instead, keep directly a
reference to the open() function.

This enhancement is not perfect, calling tokenize.open() can still fail if
called very late during Python finalization.  Usually, the function is called
by the linecache module which is called to display a traceback or emit a
warning.
parent 3ab745e3
...@@ -24,7 +24,6 @@ __author__ = 'Ka-Ping Yee <ping@lfw.org>' ...@@ -24,7 +24,6 @@ __author__ = 'Ka-Ping Yee <ping@lfw.org>'
__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ' __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
'Skip Montanaro, Raymond Hettinger, Trent Nelson, ' 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
'Michael Foord') 'Michael Foord')
import builtins
from codecs import lookup, BOM_UTF8 from codecs import lookup, BOM_UTF8
import collections import collections
from io import TextIOWrapper from io import TextIOWrapper
...@@ -430,11 +429,13 @@ def detect_encoding(readline): ...@@ -430,11 +429,13 @@ def detect_encoding(readline):
return default, [first, second] return default, [first, second]
_builtin_open = open
def open(filename): def open(filename):
"""Open a file in read only mode using the encoding detected by """Open a file in read only mode using the encoding detected by
detect_encoding(). detect_encoding().
""" """
buffer = builtins.open(filename, 'rb') buffer = _builtin_open(filename, 'rb')
encoding, lines = detect_encoding(buffer.readline) encoding, lines = detect_encoding(buffer.readline)
buffer.seek(0) buffer.seek(0)
text = TextIOWrapper(buffer, encoding, line_buffering=True) text = TextIOWrapper(buffer, encoding, line_buffering=True)
...@@ -657,7 +658,7 @@ def main(): ...@@ -657,7 +658,7 @@ def main():
# Tokenize the input # Tokenize the input
if args.filename: if args.filename:
filename = args.filename filename = args.filename
with builtins.open(filename, 'rb') as f: with _builtin_open(filename, 'rb') as f:
tokens = list(tokenize(f.readline)) tokens = list(tokenize(f.readline))
else: else:
filename = "<stdin>" filename = "<stdin>"
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment