Search code examples
pythonclosuresiterable-unpacking

Can we return 2 inner functions from 1 outer functions?


I have a function factory(takes n as variable initialized to zero) with two inner functions current(returns the value of n) and counter(which returns the value n+1).

def factory(n=0):    
    
    def counter():     
        return n+1    
    return counter
        
    def current():
        return n
    return current
        
f_current,f_counter=factory(int(input()))

I'm getting TypeError: cannot unpack non-iterable function object


Solution

  • Yes you can, but you need to have only one return statement. Otherwise, the first return statement wins, and the second is never run. Here's an example:

    def factory(n=0):    
        
        def counter():     
            return n+1    
            
        def current():
            return n
    
        return current, counter
            
    f_current, f_counter = factory(int(input()))