assigning to nested variables

Michael Hudson mwh at python.net
Fri Nov 23 05:16:37 EST 2001


John Thingstad <john.thingstad at chello.no> writes:

> I tried to create the followin callback function in Python 2.1
> 
> from __future__ import nested_scopes
> 
>     def ask(self, pattern):
>         """Ask
>         Ask if query sentence is true; return 0 otherwise 1."""
>         cPattern = self.convertClause(pattern)
> 
>         found = 0
>         def match(bindings): global found; found = 1; return 1
>         self.backChainEach(cPattern, match)
>         return found
> 
> The ide was to assign 1 to found if the match callback function was
> called.
> However, found = 1 creates a new local variable found and ask's
> found variable remains zero.

I don't think that's what's going on actually.  There are three scopes
at play:

      ,-----------------------------,
      |        global scope         |
      | ,-------------------------, |
      | |    ask's local scope    | |
      | | ,---------------------, | |
      | | | match's local scope | | |
      | | `---------------------' | |
      | `-------------------------' |
      `-----------------------------'

There are two variables called "found"; one is in the global scope,
one is in ask's local scope.  The assignment in match affects the one
in global scope.  If there was no "global found" statement in match,
then there would still be too variables called "found", one in ask's
local scope and one in match's, and the assignment would affect the
latter.

> Is there a way to assign 1 to ask's found?

Not from match's scope, no.

Here's one workaround:

class Finder:
    def __init__(self):
        self.found = 0
    def match(self, bindings):
        self.found = 1

[...]

    def ask(self, pattern):
        cPattern = self.convertClause(pattern)
        finder = Finder()
        self.backChainEach(cPattern, finder.match)
        return finder.found

but it looks like you've provided yourself a pretty inconvenient
interface to work with.

>  I read the documantation but found no refrerence to this.

It's implied but not spelled out in:

    http://python.sourceforge.net/devel-docs/ref/definitions.html

Cheers,
M.

-- 
  Unfortunately, nigh the whole world is now duped into thinking that 
  silly fill-in forms on web pages is the way to do user interfaces.  
                                        -- Erik Naggum, comp.lang.lisp



More information about the Python-list mailing list