nested function returning outer function [python]

I have a common pattern that goes like

def f(x):
  if x.type == 'Failure':
     # return `x` immediately without doing work
     return x
  else:
  # do stuff with x...
  return x

I would like to abstract the if/else pattern into a stand alone function. However I want that function, when called from inside f, to return from f immediately. Else it should just return x to a value inside f for further processing. Something like

def g(x):
  if x.type == 'Failure':
    global return x
  else:
    return x.value

def f(x):
  x_prime = g(x) # will return from f
                 # if x.type == 'Failure'
  # do some processing...
  return x_prime

Is this possible in Python?

1 answer

  • answered 2018-11-08 01:19 dmvianna

    I'm using Validation from my branch of pycategories:

    def fromSuccess(fn):
        """
        Decorator function. If the decorated function
        receives Success as input, it uses its value.
        However if it receives Failure, it returns
        the Failure without any processing.
        Arguments:
            fn :: Function
        Returns:
            Function
        """
        def wrapped(*args, **kwargs):
            d = kwargs.pop('d')
            if d.type == 'Failure':
                return d
            else:
                kwargs['d'] = d.value
            return fn(*args, **kwargs)
        return wrapped
    
    @fromSuccess
    def return_if_failure(d):
        return d * 10
    
    return_if_failure(d = Failure(2)), return_if_failure(d = Success(2))
    
    >>> (Failure(2), 20)