3

Suppose I want to reuse some code, name it "function C" whose usage falls only under the scope of "function R". Nesting the function definition within R, serves to restrict its name in the local scope (the simplest possible closure, if it can be called such). Function C is not supposed to be returned, have any side effects or even refer to its outer scopes (except globals and imported modules)

def R(x):
    def C(y):
        return y

    return C(x)

For a large number of R() calls, does this introduce any performance penalty over:

def C(x):
    return x

def R(x)
    return C(x)

Even if I import a module in the global scope and use it from within the closure, timings seem the same for both, if not faster for the first variation.

Excluding the accidental use of nonlocal variables, are there any pitfalls that make such usage of closures redundant or bug prone?

Note: I know that conformance to "Flat is better than nested" and readability of such constructs may be disputed but my question is oriented towards reasons other than readability and alike.

digenishjkl
  • 154
  • 1
  • 12
  • What *are* your reasons for doing this? If you don't want `C` called from outside `R`, you could call it `_C`. This means that you can use it elsewhere if you later realise it wasn't only needed in `R`. – jonrsharpe Feb 08 '14 at 15:25
  • 2
    There *should* be a slight but measurable performance difference, as the first constructs a new function object on each call to `R` while the latter only performs a global lookup. Edit: My timing confirm this, I get 0.72µs/loop for the first and 0.56µs/loop for the second. –  Feb 08 '14 at 17:03
  • I see. Maybe I should have used a larger (or statement-rich) body for C() to get more accurate results. I was hopping that python will treat it the same way it treats constants since it doesn't access its enclosing scope. I am in search for the proper term, I guess "constructs a new function" describes it from a point of view too abstract too lead me to background information, yet I don't know where and how to look for such information. – digenishjkl Feb 08 '14 at 19:35

0 Answers0