SHOW:
|
|
- or go back to the newest paste.
| 1 | from __future__ import print_function | |
| 2 | ||
| 3 | class deferrable(object): | |
| 4 | def __init__(self, f): | |
| 5 | self.f = f | |
| 6 | self.deferred = None | |
| 7 | self.dargs = None | |
| 8 | self.dkwargs = None | |
| 9 | ||
| 10 | def register_defer(self, df, *args, **kwargs): | |
| 11 | self.deferred = df | |
| 12 | self.dargs = args | |
| 13 | self.dkwargs = kwargs | |
| 14 | - | g = self.f.func_globals |
| 14 | + | |
| 15 | def __call__(self, *fargs, **fkwargs): | |
| 16 | if hasattr(self.f, "func_globals"): | |
| 17 | g = self.f.func_globals | |
| 18 | elif hasattr(self.f, "__globals__"): | |
| 19 | g = self.f.__globals__ | |
| 20 | else: | |
| 21 | raise NotImplementedError("What version of Python is this?")
| |
| 22 | g['defer'] = self.register_defer | |
| 23 | - | print "!!!", x, "!!!" |
| 23 | + | |
| 24 | if self.deferred: | |
| 25 | - | print "One thing:", thing1 |
| 25 | + | |
| 26 | - | print "And another:", thing2 |
| 26 | + | |
| 27 | class mock_file(object): | |
| 28 | def close(self): | |
| 29 | print("I'm closed.")
| |
| 30 | ||
| 31 | @deferrable | |
| 32 | def do_stuff(thing1, thing2): | |
| 33 | f = mock_file() | |
| 34 | defer(f.close) | |
| 35 | print("One thing:", thing1)
| |
| 36 | print("And another:", thing2)
| |
| 37 | ||
| 38 | @deferrable | |
| 39 | def do_other_stuff(thing1, thing2): | |
| 40 | def exclaim(x): | |
| 41 | print('!!!', x, '!!!')
| |
| 42 | defer(exclaim, 'done') | |
| 43 | print("One more thing:", thing1)
| |
| 44 | print("And not-quite finally:", thing2)
| |
| 45 | ||
| 46 | if __name__ == '__main__': | |
| 47 | do_stuff("foo", "bar")
| |
| 48 | do_other_stuff("foo", "bar")
| |
| 49 | ||
| 50 | """ | |
| 51 | Should print: | |
| 52 | One thing: foo | |
| 53 | And another: bar | |
| 54 | I'm closed. | |
| 55 | One more thing: foo | |
| 56 | And not-quite finally: bar | |
| 57 | !!! done !!! | |
| 58 | ||
| 59 | Note that you need to do defer(function, arguments). | |
| 60 | Doing defer(function(arguments)) executes the function | |
| 61 | immediately. Not sure if this is preventable. | |
| 62 | """ |