0

I have a question regarding a tutorial problem.

Write a function make_monitored that takes as input a function, f, that itself takes one input. The result returned by make_monitored is a third function, say mf, that keeps track of the number of times it has been called by maintaining an internal counter. If the input to mf is the special string "how-many-calls?", then mf returns the value of the counter. If the input is the special string "reset-count", then mf resets the counter to zero. For any other input, mf returns the result of calling f on that input and increments the counter.

I have the following solution which works, surprisingly.

def make_monitored(f):
    calls=[0]
    def helper(n):
        if n=="how-many-calls?":
            return calls[0]
        elif n=="reset-count":
            calls[0]=0 
        else:
            calls[0]+=1
            return f(n)
    return helper

I recalled reading about UnboundLocalError here: UnboundLocalError in Python

My question would be why won't calls[0]+=1 trigger that error? I made an assignation to a variable outside the local scope of the third function helper , and it seems a similar solution that uses instead calls.append(1) (the rest of the code correspondingly becomes len(calls) and calls.clear()) also bypasses that error.

Prashin Jeevaganth
  • 1,223
  • 1
  • 18
  • 42
  • Because you're mutating the object already bound to `calls`, not replacing it. Try `calls = [1]` instead of `calls[0] += 1` and you'll see the error. – jonrsharpe Apr 07 '18 at 15:40
  • @jonrsharpe so if object A is outside the local scope, and I modify object B bound to object A, it doesn't count as UnboundLocalError as long as I don't directly assign a value to object A? – Prashin Jeevaganth Apr 07 '18 at 15:46

0 Answers0