Question

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

Was it helpful?

Solution

Use lambdas instead!

y = lambda a: a[0] = a[1]
y([1, 2, 3])

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top