import inspect
import types

def get_cc():
	"""Generate the current continuation."""
	up_frame = inspect.currentframe().f_back

	def copy_code(base, co_code):
		"""Copy a code object, but change the code"""
		return types.CodeType(base.co_argcount,
		                      base.co_kwonlyargcount,
		                      base.co_nlocals,
		                      base.co_stacksize,
		                      base.co_flags,
		                      co_code,
		                      base.co_consts,
		                      base.co_names,
		                      base.co_varnames,
		                      base.co_filename,
		                      base.co_name,
		                      base.co_firstlineno,
		                      base.co_lnotab,
		                      base.co_freevars,
		                      base.co_cellvars)

	# In this case, the call to get_cc and the resulting assignment to a global variable
	# is 4 bytes worth of bytecode.
	new_code = copy_code(up_frame.f_code, up_frame.f_code.co_code[up_frame.f_lasti + 6:])
	return new_code


def call_cc(cont):
	"""Call the current continuation"""
	exec(cont)


cc, bar = None, 0

def func():
	global cc
	print("This should show only once")
	cc = get_cc()
	global bar
	print(bar)
	bar += 1

func()
call_cc(cc)
call_cc(cc)
call_cc(cc)