0

I have a number of methods that are of the following format:

def p_methodone(a):
    pass

def p_methodtwo(a):
    pass

...

I would like to remove the pass and populate these methods with the code a[0] = a[1]. Is it possible to do this in Python dynamically using something like reflection? The reason being is that I have a lot of these methods, and the code a[0] = a[1] might change later on - it would be nice to have to only change it in one place (instead of doing a search and replace).

(Note: I can't alter these definitions in any way since an external library relies on them being in this format.)

sdasdadas
  • 23,917
  • 20
  • 63
  • 148
  • 1
    Is it possible that some other part of the program has gotten a reference to the function you wish to change? If so, those parts will still have the old function after rebinding the name like sfk and Rustam suggests. A solution that should work even in this case is presented in the talk [Don't Do This: Some things you should never do in python](http://www.reddit.com/r/programming/comments/1hu12x/dont_do_this_some_things_you_should_never_do_in/). It involves messing around with the `__code__` attribute. This is only of academic interest of course, since you *shouldn't* do that. :) – Lauritz V. Thaulow Aug 02 '13 at 07:55

2 Answers2

1

Use lambdas instead!

y = lambda a: a[0] = a[1]
y([1, 2, 3])
Rustam Safin
  • 812
  • 7
  • 15
0

You can override a function definition with a lambda function or with another function

>>> def newdef(a): return a+1
... 
>>> p_methodone = newdef
>>> p_methodone(10)
11

>>> def newdef(a): return a+2
... 
>>> p_methodone = newdef
>>> p_methodone(10)
12
sfk
  • 709
  • 5
  • 14