Search code examples
pythonyamlruamel.yaml

Why does `from ruamel.yaml import CSafeDumper` throw an import error when executed on python3.11?


Create a test.py that contains

import sys
print(sys.version)
from importlib.metadata import version
print(f"ruamel.yaml version {version('ruamel.yaml')}") 

from ruamel.yaml import CSafeDumper

Running python3.11 test.py on will generate

3.11.3 (main, Apr  5 2023, 14:14:37) [GCC 11.3.0]
ruamel.yaml version 0.17.22
Traceback (most recent call last):
  File "/home/victory/test.py", line 6, in <module>
    from ruamel.yaml import CSafeDumper
ImportError: cannot import name 'CSafeDumper' from 'ruamel.yaml' (/home/victory/venv_3.11/lib/python3.11/site-packages/ruamel/yaml/__init__.py)

python3.10 test.py on the other hand, returns

3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0]
ruamel.yaml version 0.17.22

I don't know if this is a bug or if something has changed in ruamel.yaml in the latest python version. https://pypi.org/project/ruamel.yaml/0.17.22/ doesn't mention anything about this as far as i can tell.


Solution

  • From the GCC 11.3.0, I assume you are running on Linux. You don't describe how you installed, but it looks like you only have ruamel.yaml installed and not ruamel.yaml.clib, which is needed for the CSafeDumper to become active.

    For Python 3.10 that installation of ruamel.yaml.clib is automatic, but for Python 3.11 it is not (it will be in the next release of ruamel.yaml).

    On a machine running Ubuntu 22.04, in a freshly created virtualenv:

    ➜ ~ /opt/util/rytest2/bin/python -m pip list               
    Package          Version
    ---------------- -------
    pip              22.3.1
    ruamel.yaml      0.17.22
    ruamel.yaml.clib 0.2.7
    setuptools       65.5.0
    ➜ ~ /opt/util/rytest2/bin/python            
    Python 3.11.3 (main, Apr 13 2023, 08:44:49) [GCC 11.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from ruamel.yaml import CSafeDumper
    >>> print(CSafeLoader)
    <class 'ruamel.yaml.cyaml.CSafeDumper'>
    >>> 
    

    So just explicitly installing ruamel.yaml.clib should do the trick.