Pyyaml: yaml.constructor.ConstructorError with loading argparse.Namespace

Created on 21 Jan 2021  路  2Comments  路  Source: yaml/pyyaml

We have a problem with dumping the python native namespace, see the example below...

from argparse import Namespace

import yaml

data = {"namespace": Namespace(bar='buzz')}

config_yaml = 'testik.yaml'
with open(config_yaml, "w", newline="") as fp:
    yaml.dump(data, fp)

with open(config_yaml, "r") as fp:
    data2 = yaml.load(fp)

print(data2)

fails with following error:

yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/object:argparse.Namespace'
  in "testik.yaml", line 1, column 12

I have tested and it fails for recent PyYAML==5.4.x

btw, could be related to #64

Most helpful comment

You need to explicitly use UnsafeLoader or unsafe_load now
This was a security fix for 5.4, see https://github.com/yaml/pyyaml/issues/420

yaml.load(fp, Loader=yaml.UnsafeLoader)
# or
yaml.unsafe_load(fp)

All 2 comments

You need to explicitly use UnsafeLoader or unsafe_load now
This was a security fix for 5.4, see https://github.com/yaml/pyyaml/issues/420

yaml.load(fp, Loader=yaml.UnsafeLoader)
# or
yaml.unsafe_load(fp)

To elaborate on what perlpunk said above: this is an expected side-effect of disallowing FullLoader to construct arbitrary Python objects (the dumper was not affected and is working fine in this case). Rather than continue the game of CVE Whack-a-Mole trying to blacklist functionality in FullLoader, code that needs to construct arbitrary Python objects via the python/object tag variants needs to use a loader that supports that- going forward, that's either UnsafeLoader (which will work with any object definition it can locate), or a custom loader where you've explicitly called add_constructor on it for each object type you need to support.

Closing, since this is expected behavior.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sigmavirus24 picture sigmavirus24  路  8Comments

lucj picture lucj  路  7Comments

perrygeo picture perrygeo  路  8Comments

petmakris picture petmakris  路  3Comments

jeoffridavis picture jeoffridavis  路  4Comments