Can we return 2 inner functions from 1 outer functions?

Viewed 83

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

2 Answers

Functions terminate as soon as they encounter the return statement. Hence, your factory function terminates when it sees return counter. You can change it as follows (return after defining both the functions).

def factory(n=0):
    def counter():     
        return n+1
        
    def current():
        return n

    return current, counter
        
f_current,f_counter=factory(int(input()))

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()))
Related