import disimport newclass MissingLabelError(Exception):”goto’ without matching ‘label’.”passdef goto(fn):”A function decorator to add the goto command for a function.Specify labels like so:label .fooGoto labels like so:goto .foo”labels = {}gotos = {}globalName = Noneindex = 0end = len(fn.func_code.co_code)i = 0# scan through the byte codes to find the labels and gotoswhile i < end:op = ord(fn.func_code.co_code[i])i += 1name = dis.opname[op]if op > dis.HAVE_ARGUMENT:b1 = ord(fn.func_code.co_code[i])b2 = ord(fn.func_code.co_code[i+1])num = b2 * 256 + b1if name == ‘LOAD_GLOBAL’:globalName = fn.func_code.co_names[num]index = i – 1i += 2continueif name == ‘LOAD_ATTR’:if globalName == ‘label’:labels[fn.func_code.co_names[num]] = indexelif globalName == ‘goto’:gotos[fn.func_code.co_names[num]] = indexname = Nonei += 2# no-op the labelsilist = list(fn.func_code.co_code)for label,index in labels.items():ilist[index:index+7] = [chr(dis.opmap[‘NOP’])]*7# change gotos to jumpsfor label,index in gotos.items():if label not in labels:raise MissingLabelError(“Missing label: %s”%label)target = labels[label] + 7 # skip NOPsilist[index] = chr(dis.opmap[‘JUMP_ABSOLUTE’])ilist[index + 1] = chr(target & 255)ilist[index + 2] = chr(target >> 8)# create new function from existing functionc = fn.func_codenewcode = new.code(c.co_argcount,c.co_nlocals,c.co_stacksize,c.co_flags,”.join(ilist),c.co_consts,c.co_names,c.co_varnames,c.co_filename,c.co_name,c.co_firstlineno,c.co_lnotab)newfn = new.function(newcode,fn.func_globals)return newfnif __name__ == ‘__main__’:@gotodef test1(n):s = 0label .myLoopif n <= 0:return ss += nn -= 1goto .myLoopassert(test1(10) == 55) aslında verdiğim kodun sonu herşeyi açıklıyor. Python dilinde goto diye bir komut yok ancak adam kendisi eklemiş. Bu kodu gördüğümde ben kendimden geçtim sizde nasıl bir etki yaratır bilemiyorum. Bu arada kodun aslı bana ait değildir, alıntıdır.
Kodun aslı