Search code examples
pythonfunctionreturn

How to 'pass on' a return value?


I have class with several functions that compute some quantities. A global Boolean controls if the functions should either return the value or store it as an attribute. I want to have a single _return_value() function that accomplishes this, rather than writing if store_value … else return … in each of the class functions. A simple _return_value = return gives a syntax error. Here is a minimal (not) working example:

class foo(object):
    def __init__(self, store_value=False):

        if store_value:
            self._return_function = self._store_value
        else:
            self._return_function = self._return_value

    def _return_value(self, value):
        return value

    def _store_value(self, value):
        setattr(self, 'stored_value', value)

    def add_one(self, value):
        self._return_function(value+1)

It works perfectly for storing the value as a class attribute, i.e.

objFoo = foo(store_value=True)
objFoo.add_one(41)
print(objFoo.stored_value)  # prints '42'

But the add_one() function returns None when I use

objFoo2 = foo(store_value=False)
print(objFoo2.add_one(41))  # expect to return '42', but returns 'None'

How do I manage that _return_value() returns the value 'all the way' so that add_one() returns 42 in this case?


Solution

  • Have add_one forward _return_function's return value.

    def add_one(self, value):
        return self._return_function(value+1)
    
    • If _return_function is set to _store_value then add_one will return None.
    • If _return_function is set to _return_value then add_one will forward the returned value.