Question

In dynamic languages like Python i know it possible to convert easily YAML mappings to objects. It can be be a very powerful feature and save a lot of coding.

I'm facing a problem when i try to map the .yaml file to an object.

File: objtest.yaml

---
  test: yaml test   
  option: this is option
...

My Code:

class MyTest(object):
    pass

testObj = MyTest()

f = open(os.path.join(os.path.dirname(__file__), 'objtest.yaml'))

rawData = yaml.safe_load(f)

print rawData

testObj.__dict__ = yaml.load(f)

f.close()

print testObj

STDOUT (with trace back):

{'test': 'yaml test', 'option': 'this is option'}
Traceback (most recent call last):
  File "C:/CROW/ATE/Workspace/Sandbox/test.py", line 23, in <module>
    testObj.__dict__ = yaml.load(f)
TypeError: __dict__ must be set to a dictionary, not a 'NoneType'

Question:

As you can see the file is loaded to rawData but the class instance testObj has a problem when I try to load the .yaml file to it.

Any ideas what i'm doing wrong?

Was it helpful?

Solution

rawData = yaml.safe_load(f) reads the file, and that means the later yaml.load(f) can't read any more data from the file. While you could rewind the seek pointer, there is absolutely no reason to: You've already loaded the YAML document (in a manner that is safer, too). Just do testObj.__dict__ = rawData.

That said, I have reservations about assigning to __dict__. It may or may not be implementation-defined, and in any case it reeks of a hack. There's zero validation, invalid data leads to a type error or attribute error (or with YAML.load instead of safe_load, even arbitrary other errors, including silent security breaches) later on in the program with no indication that the YAML file is at fault. A proper serialization library is a more robust and maintainable choice in the long run.

OTHER TIPS

Not sure exactly what you are trying to do... Take a look at http://pyyaml.org/wiki/PyYAMLDocumentation about halfway down on the section on Constructors, Representers, Resolvers. If you really want your object to be able to be loaded, you want to create a SafeRepresenter and SafeConstructor for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top