Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I merge two functions in one function?

Let there are some codes like

def f(a, b):
    # some code (no return)

def g(c, d, e):
    # some code (no return)

Then, I want to make a function "merge_functions" which

h = merge_functions(f, g)

works same with:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def h(a, b, c, d, e):
    f(a, b)
    g(c, d, e)

There could be more or fewer parameters in f and g, and I want to keep the name of the parameters the same.

There is no default value in any parameters.

I have tried:

from inspect import signature

getarg = lambda func: list(dict(signature(func).parameters).keys())
to_arg_form = lambda tup: ', '.join(tup)
def merge_functions(f, g):
    fl = getarg(f)
    gl = getarg(g)
    result = eval(f"lambda {to_arg_form(fl+gl)}:{f.__name__}({to_arg_form(fl)}) and False or {g.__name__}({to_arg_form(gl)})")
    return result

However, I could only use this function in the same file, not as a module.
How can I make the function that can also be used as a module?

>Solution :

You can try something like this code which creates a third function which you can use everywhere:

def f1(x1, x2, **args):
    print(f"{x1} {x2}")

def f2(x1, x3, x4, **args):
    print(f"{x1} {x3} {x4}")

def merge(f1, f2):
    return lambda **args: (f1(**args), f2(**args))

f3 = merge(f1, f2)

f3(x1=1, x2=2, x3=3, x4=4)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading