YAML does not call the constructor

python, python-3.x, yaml

Solution

From the documentation:

yaml.YAMLObject uses metaclass magic to register a constructor, which transforms a YAML node to a class instance, and a representer, which serializes a class instance to a YAML node.

Internally, the default `constructor` registered by `yaml.YAMLObject` will call `YourClass.__new__` then set the fields on your class by using `instance.__dict__`. See this method for more detail.

Depending on what you want to do, you could either put some logic in `Step.__new__` (but you won't be getting any of the fields in `**kwargs`, or register a custom constructor.

Problem

I've tried following the instructions here, which led me to this code: ``` import yaml class Step(yaml.YAMLObject): yaml_tag = "!step" def __init__(self, *args, **kwargs): raise Exception("Intentionally.") yaml.load(""" --- !step foo: bar ham: 42 """) ``` Expected behaviour: I get an exception. But what I observe is, that my YAML markup results in a `Step` instance and I'm able to work with it, access methods, attributes (like `foo` in the code above) and so on. Reading the documentation, I cannot find my mistake since it suggests that the constructor is called with all the key-value-pairs as keyword arguments. Basically the example in the doc works, but not because of the constructor's implementation, but because of the fact that the key-value-pairs (properties of the `Monster`) are used to fill the object's dict. Anyone here knows about that? I'm working with python3 but did a quick evaluation in python2 and observed the same. edit What I wanted to do: To stay in the linked example (documentation), if the `Monster`s `name` starts with a `B`, double the value of `ac`.

Original source