Re: PyYAML constructor with mixed attributes

Kirill Simonov <[email protected]>
Newsgroups gmane.text.yaml.general
Message-ID <[email protected]>
Hi Fabrizio,

> Using the python object constructor capability of YAML, I am trying to
> saparate object attributes in those that are not configurable (set at
> init time by the application code) and in those that are configurable
> (loaded at init time by YAML). One possible solution is in the following
> example. I dont like it very much, there is any better way to do it?
> Thanks in advance for any help.

PyYAML uses the pickle protocol (see PEP 307) to construct YAMLObject 
instances and thus it never calls the __init__ constructor.  By default, 
PyYAML simply updates the __dict__ dictionary with the content of the 
YAML node.  You may override this behavior by providing a __setstate__ 
method accepting a single argument 'state', which is the node content.

For instance, if you add a __setstate__ method to your Test class, the 
object corresponding to the document:

--- !Test
yaml_attr: attribute from yaml

will be constructed in the following way:

obj = create a new Test object, but don't call Test.__init__()
obj.__setstate__({'yaml_attr': 'attribute from yaml'})
return obj

Thanks,
Kirill

------------------------------------------------------------------------------
SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada.
The future of the web can't happen without you.  Join us at MIX09 to help
pave the way to the Next Web now. Learn more and register at
http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.