2.7 source import in python 3.x

Robin Becker robin at reportlab.com
Mon Apr 4 07:51:27 EDT 2016


On 04/04/2016 12:15, Peter Otten wrote:
..........
>
> 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...
....

maybe two steps ahead :(

when I execute the example with python 3.4.2

> C:\code\hg-repos\reportlab>cat tmp\t1.py
> import importlib.util
> import sys
>
> # For illustrative purposes.
> import tokenize
> file_path = tokenize.__file__
> module_name = tokenize.__name__
>
> spec = importlib.util.spec_from_file_location(module_name, file_path)
> module = importlib.util.module_from_spec(spec)
> spec.loader.exec_module(module)
> # Optional; only necessary if you want to be able to import the module
> # by name later.
> sys.modules[module_name] = module
>
> C:\code\hg-repos\reportlab>\python34\python tmp\t1.py
> Traceback (most recent call last):
>   File "tmp\t1.py", line 10, in <module>
>     module = importlib.util.module_from_spec(spec)
> AttributeError: 'module' object has no attribute 'module_from_spec'

The example does work in python 3.5.0 so I guess the docs are a bit misleading.


-- 
Robin Becker




More information about the Python-list mailing list