Search code examples
pythonfunctionpython-object

Getting inputs to a function from a python object


I have a class. This class has a list of functions that are to be evaluated by a different program.

class SomeClass(object):
    def __init__(self, context):
        self.functions_to_evaluate = []

There is a function that adds functions to an instance of SomeClass, via something like:

new_function = check_number(5)
SomeClassInstance.functions_to_evaluate.append(new_function)

Where check_number is a function that will check if number is greater than 10, let's say.

If I take SomeClassInstance.functions_to_evaluate and print it, I get a bunch of python objects, like so:

<some_library.check_number object at 0x07B35B90>

I am wondering if it is possible for me to extract the input given to check_number, so something like:

SomeClassInstance.functions_to_evaluate[0].python_feature() that will return "5" or whatever the input to check_number was to me.


Solution

  • You can use the standard library functools.partial, which creates a new partially applied function *.

    >>> from functools import partial
    >>> def check_number(input):
    ...     return input > 10
    >>> fn = partial(check_number, 5)
    >>> fn.args  # this attribute gives you back the bound arguments, as a tuple.
    (5,)
    >>> fn()  # calls the function with the bound arguments.
    False
    

    *: actually the partial object is not a function instance, but it is a callable, and from a duck-type perspective it's a function.