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

Skip to content

Commit 16475ad

Browse files
committed
Issue #13959: Re-implement imp.load_source() in imp.py.
1 parent 4132368 commit 16475ad

2 files changed

Lines changed: 28 additions & 391 deletions

File tree

Lib/imp.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from _imp import (get_magic, get_tag, get_suffixes, cache_from_source,
1515
source_from_cache)
1616
# Should be re-implemented here (and mostly deprecated)
17-
from _imp import (find_module, load_compiled, load_source, NullImporter,
17+
from _imp import (find_module, load_compiled, NullImporter,
1818
SEARCH_ERROR, PY_SOURCE, PY_COMPILED, C_EXTENSION,
1919
PY_RESOURCE, PKG_DIRECTORY, C_BUILTIN, PY_FROZEN,
2020
PY_CODERESOURCE, IMP_HOOK)
@@ -25,6 +25,33 @@
2525
import os
2626

2727

28+
class _LoadSourceCompatibility(_bootstrap._SourceFileLoader):
29+
30+
"""Compatibility support for implementing load_source()."""
31+
32+
def __init__(self, fullname, path, file=None):
33+
super().__init__(fullname, path)
34+
self.file = file
35+
36+
def get_data(self, path):
37+
"""Gross hack to contort SourceFileLoader to deal w/ load_source()'s bad
38+
API."""
39+
if path == self._path:
40+
with self.file:
41+
# Technically should be returning bytes, but
42+
# SourceLoader.get_code() just passed what is returned to
43+
# compile() which can handle str. And converting to bytes would
44+
# require figuring out the encoding to decode to and
45+
# tokenize.detect_encoding() only accepts bytes.
46+
return self.file.read()
47+
else:
48+
return super().get_data(path)
49+
50+
51+
def load_source(name, pathname, file=None):
52+
return _LoadSourceCompatibility(name, pathname, file).load_module(name)
53+
54+
2855
def load_package(name, path):
2956
if os.path.isdir(path):
3057
extensions = _bootstrap._suffix_list(PY_SOURCE)

0 commit comments

Comments
 (0)