[ create a new paste ] login | about

Link: http://codepad.org/6vAY8Leh    [ raw code | output | fork ]

aaronla - Python, pasted on Feb 26:
def adds_dynamic_z_decorator(f):
  def replacement(*arg,**karg):
    # create a new 'z' binding in globals, saving previous
    if 'z' in globals():
      oldZ = (globals()['z'],)
    else:
      oldZ = None
    try:
      globals()['z'] = None
      #invoke the original function
      res = f(*arg, **karg)
    finally:
      #restore any old bindings
      if oldZ:
        globals()['z'] = oldZ[0]
      else:
        del(globals()['z'])
    return res
  return replacement

@adds_dynamic_z_decorator
def func(x,y):
  print z

def other_recurse(x):
  global z
  print 'x=%s, z=%s' %(x,z)
  recurse(x+1)
  print 'x=%s, z=%s' %(x,z)

@adds_dynamic_z_decorator
def recurse(x=0):
  global z
  z = x
  if x < 3:
    other_recurse(x)

print 'calling func(1,2)'
func(1,2)

print 'calling recurse()'
recurse()


Output:
1
2
3
4
5
6
7
8
9
calling func(1,2)
None
calling recurse()
x=0, z=0
x=1, z=1
x=2, z=2
x=2, z=2
x=1, z=1
x=0, z=0


Create a new paste based on this one


Comments: