Default scope of variables

Joshua Landau at
Thu Jul 4 07:09:04 CEST 2013

On 4 July 2013 05:36, Chris Angelico <rosuav at> wrote:
> On Thu, Jul 4, 2013 at 2:30 PM, Joshua Landau
> < at> wrote:
>> That said, I'm not too convinced. Personally, the proper way to do
>> what you are talking about is creating a new closure. Like:
>> for i in range(100):
>>     with new_scope():
>>         for i in range(100):
>>             func(i)
>>     func(i) # Using i from original loop
>> But it's not like Python'll ever support that.
> def foo():
>   for i in range(3):
>     print("outer",i)
>     def inner():
>       for i in range(4):
>         print("inner",i)
>     inner()
>     print("outer",i)
> That works, but you then have to declare all your nonlocals, and it
> hardly reads well.

Unfortunately that's what people, I included, end up doing. Stuff like:

def paranoia(...):
    def safe_recursive(...):
    return safe_recursive
safe_recursive = paranoia()

is blimmin ugly. Then you're only really left with

class safe_recursive:
    def __call__(self, ...):

which only solves it for recursive functions.

I guess this means I actually agree with your sentiment, just not the specifics.

More information about the Python-list mailing list