Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #106432 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2016-04-04 13:15 +0200 |
| Last post | 2016-04-04 13:15 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: 2.7 source import in python 3.x Peter Otten <__peter__@web.de> - 2016-04-04 13:15 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2016-04-04 13:15 +0200 |
| Subject | Re: 2.7 source import in python 3.x |
| Message-ID | <mailman.10.1459768597.32530.python-list@python.org> |
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.
>
Back to top | Article view | comp.lang.python
csiph-web