|
From: Faheem M. <fa...@fa...> - 2013-01-24 09:03:47
|
Hi,
I'm planning to use PyYAML for a configuration file. Some of the items in
that configuration file are Python tuples of tuples. So, I need a
convenient way to represent them. One can represent Python tuples of
tuples as follows using PyYAML
print yaml.load("!!python/tuple [ !!python/tuple [1, 2], !!python/tuple [3, 4]]")
However, this is not convenient notation for a long sequence of items. I
think it should be possible to define a custom tag, like
python/tuple_of_tuples
See my attempt to define this below, by mimicking how python/tuple is
defined, and trying to do similar subclassing. It fails, but gives an idea
what I am after, I think. A proper solution would be most welcome.
I have a couple of comments on my attempted solution.
1) I'd have thought that the constructor
`construct_python_tuple_of_tuples` would return the completed structure,
but in fact it seems to return an empty structure as follows
([], [])
However, the value that is returned is a tuple of lists of integers, so
quite close to the desired result. So, the structure must be completed
somewhere else.
The line with
tuple([tuple(t) for t in x])
was my attempt to coerce the list of tuples to a tuple of tuples, but of
course it fails since the object is not completely constructed there.
If this last bit doesn't make sense, please ignore it.
2) Not sure what is with the
yaml.org,2002
Why 2002?
Please CC me on any reply. Thanks.
Regards, Faheem
###########################################################################
import yaml
from yaml.constructor import Constructor
def construct_python_tuple_of_tuples(self, node):
#return tuple(self.construct_sequence(node))
print "node", node
x = tuple(self.construct_sequence(node))
print "x", x
foo = tuple([tuple(t) for t in x])
print "foo", foo
return x
Constructor.construct_python_tuple_of_tuples =
construct_python_tuple_of_tuples
Constructor.add_constructor(
u'tag:yaml.org,2002:python/tuple_of_tuples',
Constructor.construct_python_tuple_of_tuples)
y = yaml.load("!!python/tuple_of_tuples [[1,2], [3,4]]")
print "y", y, type(y)
print y[0], type(y[0])
print y[0][0], type(y[0][0])
############################################################################
Results
node SequenceNode(tag=u'tag:yaml.org,2002:python/tuple_of_tuples',
value=[SequenceNode(tag=u'tag:yaml.org,2002:seq',
value=[ScalarNode(tag=u'tag:yaml.org,2002:int', value=u'1'),
ScalarNode(tag=u'tag:yaml.org,2002:int', value=u'2')]),
SequenceNode(tag=u'tag:yaml.org,2002:seq',
value=[ScalarNode(tag=u'tag:yaml.org,2002:int', value=u'3'),
ScalarNode(tag=u'tag:yaml.org,2002:int', value=u'4')])])
x ([], [])
foo ((), ())
y ([1, 2], [3, 4]) <type 'tuple'>
y[0] [1, 2] <type 'list'>
y[0][0] 1 <type 'int'>
|