Description
Feature or enhancement
Importing new modules in Python is a pain, and far from straightforward. The trivial way to import a new module would be to give the full path of the file containing the required code - which could be a python init module itself, setting up a fully functional module.
Pitch
The import behaviour could change such a way that every beginner would feel involved, and we wouldn't have long discussions about importing modules.
The new behaviour - added to existing - would look like:
import 'path/to/module/module_name.py'
OR
import 'path/to/module/module_name.py' as module_name
The first one would use the filename as the module_name by default.
I'm aware that this behaviour is already solved if the path of the file is in the python path, however it only works if python starts AFTER the python path is defined AND the file is there already in the path. Which makes it very confusing using the import functionality from an ipynb notebook.
Solution proposal
import sys
import types
import importlib.machinery
define the name and path of your module
module_name = 'new_module'
module_path = '/path/to/new_module.py'
create a loader for the module
loader = importlib.machinery.SourceFileLoader(module_name, module_path)
load the source code from the .py file
code = loader.get_code(module_name)
create a new module object
new_module = types.ModuleType(loader.name)
add the source code to the module object
exec(code, new_module.__dict__)
add the module to the cache
sys.modules[loader.name] = new_module