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.)

1
  • 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. It involves messing around with the __code__ attribute. This is only of academic interest of course, since you shouldn't do that. :) Commented Aug 2, 2013 at 7:55

2 Answers 2

1

Use lambdas instead!

y = lambda a: a[0] = a[1] y([1, 2, 3]) 
Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.