Method in Methods and Variables

Jp Calderone exarkun at intarweb.us
Mon Feb 3 09:40:05 EST 2003


On Mon, Feb 03, 2003 at 03:11:50PM +0100, Thomas Guettler wrote:
> Hi!
> 
> The following python code behaves strange:
> 
> import re
> def test(my_int, my_list):
>     content='"a" "b" "c"'
>     def sub(matchObject):
>         my_string=matchObject.group(1)
>         print my_int
>         my_int+=1 # (*) If I uncomment this line it works
>         print my_list
>         return "-%s:%s-" % (my_string, my_int)
>     content=re.sub(r'"(.*?)"',
>                    sub, content)
>     print content


  Here's a simpler example:

def foo(firstLocal):
  def bar():
      print firstLocal
      firstLocal = 10
  bar()
foo(10)


  The problem is scoping rules.  firstLocal isn't local to bar()'s nested
scope.  Trying to rebind it -after- reading it from the enclosing scope is
an error.  Rebinding it before reading is ok, because the name is bound in
the local scope, not the enclosing scope, and then it behaves just as a
local variable.

  To resolve the problem you're having above, use a mutable object instead
of an integer.  A trivial example would be to use a list, and append None,
then use the length of the list as your counter.  Another solution would be
to use an instance of a class with an integer attribute that could be
rebound.  Anything, as long as the variable from the enclosing scope doesn't
have to be bound to a new object.

  Jp

-- 
A sad spectacle.  If they be inhabited, what a scope for misery 
and folly.  If they be not inhabited, what a waste of space.
                -- Thomas Carlyle, looking at the stars
-- 
 up 49 days, 17:50, 2 users, load average: 0.03, 0.03, 0.00
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030203/0b22704e/attachment.sig>


More information about the Python-list mailing list