I often want a group that's attached to an object, that sets some
state that's dependent on that object and then unsets it. I wrote a
decorator to make such groups from a generator method on the object
(in much the same way contextlib.contextmanager does for context
managers).
class GeneratorGroup(pyglet.graphics.Group):
def __init__(self, generator, parent=None):
super(GeneratorGroup, self).__init__(parent)
assert inspect.isgeneratorfunction(generator)
self.generator = generator
self.iterator = None
def set_state(self):
assert self.iterator is None
self.iterator = self.generator()
try: next(self.iterator)
except StopIteration:
raise RuntimeError, "generator didn't yield"
def unset_state(self):
assert self.iterator is not None
try: next(self.iterator)
except StopIteration:
self.iterator = None
return
raise RuntimeError, "generator didn't stop"
def groupproperty(func):
def fget(self):
try:
return getattr(self, cached_name)
except AttributeError:
def generator():
for value in func(self):
yield value
group = GeneratorGroup(generator)
setattr(self, cached_name, group)
return group
cached_name = "_cached_%s" % func.func_name
fget.func_name = "get_%s" % func.func_name
return property(fget, doc=func.func_doc)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"pyglet-users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/pyglet-users?hl=en
-~----------~----~----~----~------~----~------~--~---