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

Returning function from another function

I’m developing a package in which I want to modify incoming functions to add extra functionality. I’m not sure how I would go about doing this. A simple example of what I’m trying to do:

def function(argument):
    print(argument,end=",")

# this will not work but an attempt at illustrating what I wish to accomplish
def modify_function(original_function):
    return def new_function(arguments):
               for i in range(3):
                   original_function(arguments)
               print("finished",end="")

and running the original function:

function("hello")

gives the output: hello,

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

and running the modified function:

modified_function = modify_function(function)
modified_function(i)

gives the output: hello,hello,hello,finished

>Solution :

Credit to @Matiss for pointing out the way to do this. Adding this answer so it is documented.

def original_function(argument):
    print(argument, end=",")

def modify_function(input_func):
    # Using *args and **kwargs allows handling of multiple arguments
    # and keyword arguments, in case something more general is required.
    def new_func(*args, **kwargs):
        for i in range(3):
            input_func(*args, **kwargs)
        print("finished", end="")

    return new_func

modified_function = modify_function(original_function)
modified_function("hello")

For other kinds of modification where you want to e.g. fix some of the arguments passed in, this way will still work, but you may also make use of https://docs.python.org/3/library/functools.html#functools.partial.

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