Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a4975a9

Browse files
committed
Issue #18755: Allow imp.load_*() loaders to have get_data() called
multiple times.
1 parent f5ebd26 commit a4975a9

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

Lib/imp.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,18 @@ def __init__(self, fullname, path, file=None):
9090
def get_data(self, path):
9191
"""Gross hack to contort loader to deal w/ load_*()'s bad API."""
9292
if self.file and path == self.path:
93-
with self.file:
93+
if not self.file.closed:
94+
file = self.file
95+
else:
96+
self.file = file = open(self.path, 'r')
97+
98+
with file:
9499
# Technically should be returning bytes, but
95100
# SourceLoader.get_code() just passed what is returned to
96101
# compile() which can handle str. And converting to bytes would
97102
# require figuring out the encoding to decode to and
98103
# tokenize.detect_encoding() only accepts bytes.
99-
return self.file.read()
104+
return file.read()
100105
else:
101106
return super().get_data(path)
102107

Lib/test/test_imp.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,13 @@ def test_load_module_extension_file_is_None(self):
248248
return
249249
imp.load_module(name, None, *found[1:])
250250

251+
def test_multiple_calls_to_get_data(self):
252+
# Issue #18755: make sure multiple calls to get_data() can succeed.
253+
loader = imp._LoadSourceCompatibility('imp', imp.__file__,
254+
open(imp.__file__))
255+
loader.get_data(imp.__file__) # File should be closed
256+
loader.get_data(imp.__file__) # Will need to create a newly opened file
257+
251258

252259
class ReloadTests(unittest.TestCase):
253260

0 commit comments

Comments
 (0)