YAML

John Bokma john at castleamber.com
Thu Feb 4 18:49:21 CET 2010


Lou Pecora <pecora at anvil.nrl.navy.mil> writes:

> In article <87eil1ddjp.fsf_-_ at castleamber.com>,
>  John Bokma <john at castleamber.com> wrote:
>
>> Lou Pecora <pecora at anvil.nrl.navy.mil> writes:
>> 
>> > That's a pretty accurate description of how I transitioned to Python 
>> > from C and Fortran.
>> 
>> Not C, but C++ (but there are also C implementations): YAML, see:
>> http://code.google.com/p/yaml-cpp/wiki/HowToParseADocument
>> 
>> I use YAML now and then with Perl for both reading/writing data and for
>> debugging purposes (YAML is quite human readable, for programmers at least)
>> 
>> Of course there is also YAML support for Python:
>> http://pyyaml.org/.
>
> Well, that looks a bit more complicated than I would like, but maybe 
> it's doing more stuff than I can grok.  Here's what I needed and how I 
> did it in Python:
>
> # Make some variables
> x=1.234e-8
> y=2
> astr="An output string...whatever"
> z=4.5+1j*1.3456  # a complex number
>
> # Output them to a file already opened as fp
> outlist=[x, y, astr, z]
> repvars= repr(outlist)+"\n"
> fp.write(repvars)
>
> # Reading same list in:
> instr=fp.readline()
> inlist=eval(instr)
> x1,y1,astr1,z1= inlist
>
>
> That's what I needed.  3 lines to write or read a inhomogeneous 
> collection of variables. I can add more variables, shuffle the order, 
> whatever without messing with formatting, etc. That's pretty easy for me 
> and it's easy for anyone to see and understand what's being done.  Not 
> trying to start an argument, just showing how the former messasge I was 
> replying to made a good point about Python's way of doing things and the 
> effort to shake off old habits from other languages.

My C++ is rusty to say the least, so I can't give you an example in C++,
and the C++ version will be longer than the Python version for
sure. I use YAML, YAML::Syck to be precise, now and then in Perl. In
Perl, if $data is a reference to an arbitrary (complex) datastructure:

DumpFile( 'filename', $data ); 

writes it out and

$data = LoadFile( 'filename' );

reads it back in.

Since YAML is to some extent human readable, I now and then use it for
debugging purposes over Data::Dumper, also because the output is more
compact, e.g.

die Dump $data;

Personally I think it's good to be aware of YAML, since it's supported
by several languages and it should in general be possible to exchange
the generated YAML between them. 

-- 
John Bokma                                                               j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development



More information about the Python-list mailing list