Matthias Lohr
Matthias Lohr

Reputation: 1856

PyYAML with Python 3.x

I've a problem using the yaml (PyYAML 3.11) library in Python 3.x. When I call import yaml I get the following error:

Python 3.4.3+ (default, Oct 14 2015, 16:03:50) 
[GCC 5.2.1 20151010] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mlohr/python-libs/yaml/__init__.py", line 2, in <module>
    from error import *
ImportError: No module named 'error'

error is a file located in the yaml directory, but the __init__.py from yaml does use absolute imports. I guess that's the problem, but I#'m not sure.

In http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support is a short path about (supposed) Python 3 support, so I'm not sure if I'm using it the wrong way.

The same issue occurs (that's the way I found the problem) when using Python 3 with python scripts using yaml.

With Python 2.7 and 2.6 it works without problems.

Any idea/suggestion how to get that working?

Upvotes: 3

Views: 7966

Answers (2)

Anthon
Anthon

Reputation: 76872

Your environment is polluted. If you create a (temporary) virtualenv this works without a problem:

$ mktmpenv -p /opt/python/3.4/bin/python
Running virtualenv with interpreter /opt/python/3.4/bin/python
Using base prefix '/opt/python/3.4'
New python executable in /home/venv/tmp-504ff2573d39ad0c/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-504ff2573d39ad0c) $ pip install pyyaml
Collecting pyyaml
Installing collected packages: pyyaml
Successfully installed pyyaml-3.11
(tmp-504ff2573d39ad0c) $ python
Python 3.4.3 (default, Jun  5 2015, 09:05:22) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>> 

The most likely cause for this is that you are re-using YAML as installed for Python 2.X. The PyYAML sources are actually different for 2.x and 3.x installs.

The easiest way around this is to install and use ruamel.yaml (disclaimer: I am the author of that package), which is an upgrade for PyYAML where the sources are once more recombined.

Upvotes: 3

Ilja Everil&#228;
Ilja Everil&#228;

Reputation: 52997

It would seem that you're either using an old version of PyYAML after all or using a Python2 installation of PyYAML with Python3 as suggested in an other answer, because in your traceback we see

from error import *

which is not an absolute import. You should either upgrade, reinstall PyYAML with Python3 sources in your environment, or create a new environment for Python3 packages.

Upvotes: 5

Related Questions