Description
Now that the imp
removal has landed on main, users migrating to Python3.12 will likely need help to move to importlib
.
The current imp docs have tips on how to do just that. Great!
One caveat: the imp.load_source
has been removed from the docs a long time ago, now it is only visible is the Python2 version of the docs. So users of imp.load_source
cannot rely on the docs to help them migrate, and have to Google this. The first results on stackoverflow are a bit wrong:
- many point to
SourceFileLoader(...).load_module()
, but this is also deprecated and slated for removal in 3.12 (according to the warning) - some solutions point to
importlib.util.spec_from_file_location
, but this does not work with files that do not end with ".py"
The solution that I think is the best translation:
def imp_load_source(module_name, module_path):
loader = SourceFileLoader(module_name, module_path)
module = types.ModuleType(loader.name)
loader.exec_module(module)
return module
I think it would be beneficial to have that kind of information in the docs. Unfortunately, imp.load_source
is not officially documented, but there are several GitHub issues and SO threads discussing how to migrate code to importlib
. IMO, we should do one of:
- add it back to the docs, with explanations on how to migrate it to
importlib
- just document the migration in the release notes, in the section "Porting to Python 3.12"
What do you think?
Linked PRs
- gh-104212: Add importlib.util.load_source_path() function #105755
- gh-104212: Explain how to port imp code to importlib #105905
- gh-104212: Explain how to port imp.load_source() #105951
- [3.12] gh-104212: Explain how to port imp code to importlib (GH-105905) #105952
- gh-104212: Explain how to port imp.load_source() #105978
- [3.12] gh-104212: Explain how to port imp.load_source() (GH-105978) #106083