2.7 source import in python 3.x
Peter Otten
__peter__ at web.de
Mon Apr 4 07:15:04 EDT 2016
Robin Becker wrote:
> A user points out that this code in reportlab uses the now deprecated imp
> module
>
> def _fake_import(fn,name):
> if os.path.isfile(fn):
> import imp
> with open(fn,'rb') as f:
> imp.load_source(name,fn,f)
>
> and suggests I use importlib SourceFileLoader. Is there anything wrong
> with this code (only for use in python 3.x)
>
>
> def _fake_import(fn,name):
> from importlib import machinery
> m = machinery.SourceFileLoader(name,fn)
> try:
> return m.load_module(name)
> except FileNotFoundError:
> raise ImportError('file %s not found' % ascii(fn))
>
> the newer import machinery seems particularly complex so I'm not at all
> sure this does what I intend even though it seems to work.
Seems like Python is one step ahead in the deprecation race. Quoting
https://docs.python.org/dev/library/importlib.html#importlib.machinery.SourceFileLoader.load_module
"""
load_module(name=None)
Concrete implementation of importlib.abc.Loader.load_module() where
specifying the name of the module to load is optional.
Deprecated since version 3.6: Use importlib.abc.Loader.exec_module()
instead.
"""
In the example section they have (for 3.4 and above)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
The importlib with all its factories is a bit intimidating; perhaps it's
best to stick with imp.load_source() and wait for some simple helper
functions to appear...
> The original function is only used once like this
>
>> try:
>>
_fake_import(os.path.expanduser(os.path.join('~','.reportlab_mods')),'reportlab_mods')
>> except (ImportError,KeyError):
>> pass
>
> and is intended to allow per user actions in a config file when reportlab
> is imported.
>
More information about the Python-list
mailing list