Re: Python scope

From: Jim Meier <jim_at_no.spam.please>
Date: Thu Jul 19 2007 - 12:09:10 CST

On 19-Jul-07, at 9:48 AM, Steven Kurylo wrote:

> I've been dying to ask this since I started using python...
>
> "all variables found outside of the innermost scope are read-only
> (an attempt to write to such a variable will simply create a new local
> variable in the innermost scope, leaving the identically named outer
> variable unchanged)."
>
> Who ever thought that was a good idea?

It was sensible back when python only had two real scopes - local and
module (global). It keeps you from accidentally modifying module
(global) state without explicitly marking that you want to. The big
problem comes up when you nest a function definition:

   def make_counter(start):
     value = start
     def incr():
       value = value + 1
       return value
     return incr

The scope access policy states that, since we are assigning to value,
it's local to (each instance of) incr. This shadows the external
binding, and since the expression tried to evaluate value before
assigning to it, causes a runtime UnboundLocalError. This is very
confusing coming from other languages with full closures.

> Perl will at least warn me that I'm actually masking an outer variable
> with an inner variable. Python just leaves me wondering where I went
> wrong.

A warning would be nice. Honestly, it's never bitten me outside of
the closure case.

-J
Received on Thu Jul 19 12:09:52 2007

This archive was generated by hypermail 2.1.8 : Thu Jul 19 2007 - 12:09:55 CST