Skip to content

Instantly share code, notes, and snippets.

@1328
Created March 11, 2015 22:38
Show Gist options
  • Select an option

  • Save 1328/e55d27e12bd85306a46e to your computer and use it in GitHub Desktop.

Select an option

Save 1328/e55d27e12bd85306a46e to your computer and use it in GitHub Desktop.
decorator example
import threading
import time
from collections import defaultdict
class Effect(object):
'''
class styled decorator because you need to have some way for the
effects.starter to find the effects.stopper
The "easiest" way of doing so is a class method that registers the stopper
functions in a dictionary, but it is a bit of a pita
'''
stoppers = {}
@classmethod
def starter(cls, name):
print('start called w. {} for {}'.format(cls, name))
def wrap(method):
print('start wrapping {}'.format(method))
def inner(obj, duration):
print('inner start running {}, {}'.format(obj, duration))
method(obj, duration)
print('looking for stopper: {}'.format(name))
stop_function = cls.stoppers[name]
print('stopper found {}'.format(stop_function))
thread = threading.Thread(target=stop_function,
args = (obj, duration))
obj.effects['freeze'].add(thread)
thread.start()
return inner
return wrap
@classmethod
def stopper(cls, name):
print('stopper called w. {} for {}'.format(cls, name))
def wrap(method):
print('stop wrap called with method:{}'.format(method))
def inner(obj, *args):
print('stop inner called obj: {}, args = {}'.format(obj, args))
return method(obj, *args)
print('registering {} as stopper for {}'.format( wrap, name))
cls.stoppers[name] = inner
return wrap
class Player:
def __init__(self):
self.speed = 1.0
self.hot = 10
self.effects = defaultdict(set)
@Effect.starter('freeze')
def freeze(self, duration):
print('freeze called')
self.speed = 0.0
#thread = threading.Thread(target=self._unfreeze,
#args = (duration,))
#self.effects['freeze'].add(thread)
#thread.start()
@Effect.stopper('freeze')
def _unfreeze(self, duration):
print('unfreeze called')
time.sleep(duration)
print('done sleeping')
self.speed = 1.0
@Effect.starter('heat')
def heat(self, duration):
print('heating player')
self.hot *= 2
@Effect.stopper('heat')
def _unheat(self, duration):
time.sleep(duration) # note, could move this into the Effects decorator
#class
self.hot /= 2
print('player cooled off')
p = Player()
p.freeze(.25)
p.heat(.5)
start = time.time()
while time.time() - start < 1:
print(p.speed, p.hot)
time.sleep(.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment