Skip to content

Instantly share code, notes, and snippets.

@riccardomurri
Created November 8, 2011 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riccardomurri/1348843 to your computer and use it in GitHub Desktop.
Save riccardomurri/1348843 to your computer and use it in GitHub Desktop.
non-working example of implementing `persistent_id` on top of PyYAML
#! /usr/bin/python
import yaml
class Persistable(object):
# simulate a unique id
_unique = 0
def __init__(self, *args, **kw):
Persistable._unique += 1
self.persistent_id = ("%s.%d" %
(self.__class__.__name__, Persistable._unique))
def persistable_representer(dumper, data):
id = data.persistent_id
outfile = open(id, 'w')
outfile.write(yaml.dump(data))
outfile.close()
return dumper.represent_scalar(u'!xref', u'%s' % id)
yaml.add_representer(Persistable, persistable_representer)
def persistable_constructor(loader, node):
xref = loader.construct_scalar(node)
infile = open(xref, 'r')
value = yaml.load(infile.read())
infile.close()
return value
yaml.add_constructor(u'!xref', persistable_constructor)
class Foo(Persistable):
def __init__(self):
self.one = 1
Persistable.__init__(self)
class Bar(Persistable):
def __init__(self, foo):
self.foo = foo
Persistable.__init__(self)
# this works, but does not consider `foo` and `bar` as `Persistable` objects
foo = Foo()
bar = Bar(foo)
print "=== foo ==="
print yaml.dump(foo)
print "=== bar ==="
print yaml.dump(bar)
# this generates a "recursion depth exceeded" error
baz = Bar(Persistable())
print "=== baz ==="
print yaml.dump(baz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment