Python default parameter value replacement (last update: 2016-04-03, created: 2016-04-03) back to the list ↑
A simple code that substitutes one of the default arguments in a given function, with a new value. It's a child of a late night discussion and should probably not be used in production-quality code. Also, it doesn't add a default value for a parameter if that doesn't exist - just replaces an already existing one. Testing on Python 2.7.3 on 64-bit Windows 10.


def a(k, x=1,y=2):
  b = 5
  print k, x, y, b

def replace_default(func, param_name, value):
  argc = func.func_code.co_argcount
  defc = len(func.func_defaults)
  idx_ofc = argc - defc
  idx = func.func_code.co_varnames.index(param_name)
  if idx < idx_ofc:
    raise Exception("Doesn't have a default value")
  if idx >= argc:
    raise Exception("Not a param")
  l = list(func.func_defaults)
  l[idx - idx_ofc] = value
  func.func_defaults = tuple(l)

a(1)
replace_default(a, "x", 7)
a(1)


Output:


> test.py
1 1 2 5
1 7 2 5
【 design & art by Xa / Gynvael Coldwind 】 【 logo font (birdman regular) by utopiafonts / Dale Harris 】