[Python-ideas] PEP 572: Statement-Local Name Bindings, take three!

Steven D'Aprano steve at pearwood.info
Tue Mar 27 20:19:21 EDT 2018


On Wed, Mar 28, 2018 at 12:08:24AM +0100, Rob Cliffe via Python-ideas wrote:
> 
> On 27/03/2018 16:22, Guido van Rossum wrote:

> >The standard reply here is that if you can't tell at a glance whether 
> >that's the case, your code is too complex. The Zen of Python says 
> >"Namespaces are one honking great idea -- let's do more of those!" and 
> >in this case that means refactor into smaller namespaces, i.e. 
> >functions/methods.
> >
> This is not always satisfactory.  If your for-loop uses 20 
> already-defined-locals, do you want to refactor it into a function with 
> 20 parameters?

The standard reply here is that if your for-loop needs 20 locals, your 
function is horribly over-complex and you may need to rethink your 
design.

And if you don't think "20 locals" is too many, okay, how about 50? 100? 
1000? At some point we'll all agree that the function is too complex.

We don't have an obligation to solve every problem of excess complexity, 
especially when the nominal solution involves adding complexity 
elsewhere.

For 25 years, the solution to complex functions in Python has been to 
refactor or simplify them. That strategy has worked well in practice, 
not withstanding your hypothetical function.

If you genuinely do have a function that is so highly coupled with so 
many locals that it is hard to refactor, then you have my sympathy but 
we have no obligation to add a band-aid for it to the language.

Putting the loop variable in its own scope doesn't do anything about the 
real problem: you have a loop that needs to work with twenty other local 
variables. Any other modification to the loop will run into the same 
problem: you have to check the rest of the function to ensure you're not 
clobbering one of the twenty other variables. Special-casing the loop 
variable seems hardly justified.

If there is a justification for introducing sub-local scoping, then I 
think it needs to be something better than pathologically over-complex 
functions.


-- 
Steve


More information about the Python-ideas mailing list