nested functions - access to variables?
Alex Martelli
aleax at aleax.it
Wed Feb 26 05:42:24 EST 2003
Oleg Leschov wrote:
> hi all.
>
> suppose we have a program like this one:
> -cut-
> g = 100
>
> def a():
> g = 200
> def b():
> global g
> g = 300
> b()
> print g
>
> a()
> print g
> -cut-
>
> this thing prints 200 300, while i really need it to print 300 100.
> When I remove 'global g', it prints 200 100, as one should expect.
There is no way, in Python, for nested function b to re-bind a
name in its outer-function a. Access, no problem (as long as b
doesn't bind that name); re-bind, no way.
> If curious, the original function parses certain syntax constructing
> list-based tree from it.
> I do not want to pollute real global namespace with function-specific
> subprograms and variables..
Such needs for packaging behavior and state are typically well met by
the object-oriented mechanisms of Python.
> The other question - will there be (or already is) in Python something
> similar in functionality to variant types from FPLs?
> not counting different perversions with checking for None...
The signature-based polymorphism of Python objects is typically
what you would use to achieve similar functionality to "variant
types" (discriminated unions, in more traditional parlance).
Alex
More information about the Python-list
mailing list