Skip to content

Instantly share code, notes, and snippets.

@cdent
Last active June 28, 2018 18:32
Show Gist options
  • Save cdent/130181f02f7cb2737f81fef2ebffc8d3 to your computer and use it in GitHub Desktop.
Save cdent/130181f02f7cb2737f81fef2ebffc8d3 to your computer and use it in GitHub Desktop.

Demo difference in behaviors between pyyaml 3 and 4 when using custom tags and safe loading. Also check against a pending Ingy change.

Run tox to see it in action. The different versions will do different things. Which is right?

The key difference is that in PyYAML 3 we see ConstructorErrors from safe_load and in PyYAML 4 they are from danger mode.

import yaml
class NanChecker(yaml.YAMLObject):
yaml_tag = u'!NanChecker'
def __eq__(self, other):
try:
return math.isnan(other)
except TypeError:
return False
yaml.add_constructor(u'!IsNAN', lambda loader, node: NanChecker())
def test():
safe_load = yaml.safe_load
try:
danger_load = yaml.danger_load
except AttributeError:
try:
danger_load = yaml.python_load
except AttributeError:
print('danger_load not found, using load')
danger_load = yaml.load
test_strings = [
"foo: !IsNAN",
"foo: !NanChecker {}",
"foo: !!python/object:__main__.NanChecker {}",
]
print("#### danger load is: %s" % danger_load)
print("#### safe load is: %s" % safe_load)
for test_string in test_strings:
print("#### TRYING: %s" % test_string)
try:
safe_tag_data = safe_load(test_string)
except Exception as err:
safe_tag_data = err.__class__.__name__
try:
danger_tag_data = danger_load(test_string)
except Exception as err:
danger_tag_data = err.__class__.__name__
print('safe %s' % safe_tag_data)
print('danger %s' % danger_tag_data)
if __name__ == '__main__':
test()
[tox]
envlist = yIngy,y4,y3
basepython = python3
skipsdist = True
[testenv:yIngy]
deps = git+https://github.com/yaml/pyyaml@3dc3f5f0fc41db52e894f65cc4eec9470ffdf725
commands = python custom.py
[testenv:y4]
deps = PyYAML>=4.0
commands = python custom.py
[testenv:y3]
deps = PyYAML<4.0
commands = python custom.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment