Search code examples
pythonreflectionintrospection

Is it possible to dynamically populate Python methods with code?


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


Solution

  • Use lambdas instead!

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