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 Monsters name starts with a B, double the value of ac.
From the documentation:
Internally, the default
constructorregistered byyaml.YAMLObjectwill callYourClass.__new__then set the fields on your class by usinginstance.__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.