CodeHard_or_HardCode
CodeHard_or_HardCode

Reputation: 287

Python: Outputting data from a function called in a function

I have a function called from within a function like this:

def counter(number):
  number = number + 1
  return number

def iterator(iteration, function):
  for i in range(iteration):
    mfunction = function
    output = mfunction()
  return output

I want to call it something like this:

number = 0
number = iterator(5, partial(counter, number))
print number

This returns 1, where as it should return 5, because the count function should have been called 5 times.
I realize that somehow the data isn't outputting correctly but I can't figure out how to return out of the for loop.

This question may seem redundant, because I could easily do something like:

for i in range(5):
  number = counter(number)

But the latter example defeats the purpose of this program.

I think the problem is that I need to create an argument in the counter function to account for the iterator function. But the problem in my actual program is that I would have to modify many functions to do this, and I am trying to avoid that.

I am not that familiar with calling functions inside of functions and any help would be greatly appreciated,

Upvotes: 0

Views: 106

Answers (1)

falsetru
falsetru

Reputation: 369264

partial(counter, number) is equivalent to partial(counter, 0). So the code is calling counter(0) 5 times.

def counter(number):
    number = number + 1
    return number

def iterator(iteration, function, arg):
    for i in range(iteration):
        arg = function(arg)
    return arg

number = 0
number = iterator(5, counter, number)
print number # => 5

def counter(number, delta):
    number = number + delta
    return number

def iterator(iteration, function, *args):
    args = list(args)
    for i in range(iteration):
        ret = function(*args)
        args[0] = ret
    return ret

number = 0
number = iterator(5, counter, number, 5)
print number # => 25

Upvotes: 2

Related Questions