[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Nick Coghlan ncoghlan at gmail.com
Thu Sep 29 21:24:45 CEST 2011

On Thu, Sep 29, 2011 at 2:25 PM, Devin Jeanpierre
<jeanpierreda at gmail.com> wrote:
>> I don't think supporting monkey-patching is necessary
> Nothing is necessary. I maintain it is extremely useful for testing.
> There are entire libraries built around monkeypatching code for the
> purpose of testing it. For example, recently I saw Exocet, which
> allows you to create a new module object but replacing the imports
> with whatever you want.(The analogue here would be copying a function,
> but with new closure variables).
> Without this you can't really _unit_ test a closure, at least as I
> understand it. It becomes inextricably linked with its scope, which is
> not what you want to test.

Improving introspection of closures doesn't magically remove the need
to design for testability. Some ways of using closures are fairly easy
to test (e.g. you just call the outer function again with
monkey-patched globals and get a monkey-patched closure). Others are
not (you define excessively complex state in the closure without
provide a way to replace it for testing purposes).

If the amount of state in a closure is causing serious testing
problems, it's a hint that the code is attempting to handle a "data
with behaviour" situation more suited to an OOP style rather than an
"algorithm with state" that is particularly amenable to modelling with

Providing a nicer API for features the language already supports to
simplify whitebox testing is one thing, providing a completely new
feature (i.e. modifying closure references from outside the function)
is something else entirely.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list