[Tutor] Python scope and variable binding
spir
denis.spir at gmail.com
Fri Nov 29 09:06:20 CET 2013
On 11/29/2013 06:20 AM, eryksun wrote:
> On Wed, Nov 27, 2013 at 10:04 AM, Arnaud Legout <arnaud.legout at inria.fr> wrote:
> [...]
For what it's worth, a personal point of view on Python class defs. I ended up
undertanding class definitions as code blocks the following way:
Imagine Python has kinds of free sections of code (like Lua or C, and many other
languages), but using "section" as keyword like so, which permits to name such
sections:
section Def_Write_i:
i = 1
print(i)
Def_Write_i is a block of code, like a func, or a branch of an 'if' statement,
or a loop body. Unlike a func, it cannot be called, it is just executed on the
way. I could serve to struture code (I actually would enjoy that).
Now, add to this that such as section's scope (namespace) is permanent like an
object (like an object's __dict__), instead of transient like function scopes:
and you get classes as code blocks and namespaces. [C's function-local static
vars are somewhat similar: they remain; but unlike Python's class vars they are
not accessible from outside the func.]
In Lua, definition of an "object-like" table is similar, but unlike for Python
classes it cannot refer to itself or its own local vars, because at definition
time the object (the table) does not yet exists as such:
t = {
i = 1,
j = i+1, -- error
k = t.i+1, -- error as well
}
To reproduce the functionality of Python classes, it should be (but is not) that
the above code is equivalent to:
t = {}
t.i = 1
t.j = t.i+1
t.k = t.i+1
Also, there cannot be any other statement there but assignments.
I used to use this weird feature of Python classes to make free, permanent, and
even computable scopes. For instance, to define parsers: sets of named patterns,
with higher-level ones building on lowel-level ones:
class ArithParser(Parser):
digit = Range("0-9")
natural = String(digit)
natural.test("123") ### debug ###
integer = Comp(Option('-'), natural)
...
In addition, one can have such free namespaces initialised and given other
attributes:
arith_parser = ArithParser() # init & get instance attributes defined in Parser
Denis
More information about the Tutor
mailing list