fork download
  1. import inspect
  2. import types
  3.  
  4. def get_cc():
  5. """Generate the current continuation."""
  6. up_frame = inspect.currentframe().f_back
  7.  
  8. def copy_code(base, co_code):
  9. """Copy a code object, but change the code"""
  10. return types.CodeType(base.co_argcount,
  11. base.co_kwonlyargcount,
  12. base.co_nlocals,
  13. base.co_stacksize,
  14. base.co_flags,
  15. co_code,
  16. base.co_consts,
  17. base.co_names,
  18. base.co_varnames,
  19. base.co_filename,
  20. base.co_name,
  21. base.co_firstlineno,
  22. base.co_lnotab,
  23. base.co_freevars,
  24. base.co_cellvars)
  25.  
  26. # In this case, the call to get_cc and the resulting assignment to a global variable
  27. # is 4 bytes worth of bytecode.
  28. new_code = copy_code(up_frame.f_code, up_frame.f_code.co_code[up_frame.f_lasti + 6:])
  29. return new_code
  30.  
  31.  
  32. def call_cc(cont):
  33. """Call the current continuation"""
  34. exec(cont)
  35.  
  36.  
  37. cc, bar = None, 0
  38.  
  39. def func():
  40. global cc
  41. print("This should show only once")
  42. cc = get_cc()
  43. global bar
  44. print(bar)
  45. bar += 1
  46.  
  47. def g():
  48. func()
  49. print("This should show multiple times")
  50.  
  51. g()
  52. call_cc(cc)
  53. call_cc(cc)
  54. call_cc(cc)
Success #stdin #stdout 0.02s 30672KB
stdin
Standard input is empty
stdout
This should show only once
0
This should show multiple times
1
2
3