Can global variable be passed into Python function?

Chris Angelico rosuav at gmail.com
Fri Feb 28 10:46:39 EST 2014


On Sat, Mar 1, 2014 at 2:29 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> BTW, here's a syntax that doesn't introduce any new keywords:
>
>    with self.state from Connection.State:
>        if CONNECTING or CONNECTED:
>            ...
>        elif DISONNECTING:
>            ...
>        else:
>            ...

Okay, I understand your 'from' now. What it really does is introduce a
new scope, a read-only one presumably (because you really do NOT want
the Pandora's Box that ECMAScript's 'with' is) from which unqualified
names will be looked up. I would say that that's a very reasonable
idea, quite separately from a switch statement. Suppose you had
something like this:

with scope(Connection.State):
    if self.state == CONNECTING:
        print("I am not",DISCONNECTING)

It'd require a change to the LOAD_GLOBAL opcode to have it look in
multiple scopes. If you want to change something, be explicit about
where the change goes, but for lookups, it would be possible to have
them go to multiple places. I suspect, though, that this wouldn't fly;
I already posited such a theory, and was told that CPython's internals
made it much more convenient to not introduce infinitely nesting
scopes - the two use-cases that I'd most look at are these:

# This executes as a function
doubled = [x*2 for x in lst]

# This implicitly unbinds e in a finally clause
try:
    foo()
except Exception as e:
    pass

Neither is quite perfect; the closure method is mostly clean, but has
some extremely esoteric edge cases, and the unbinding means that a
previous value for 'e' is lost. But both are kept rather than
introducing this concept of true subscoping, because CPython's
implementation makes the latter hard.

Predicating your entire proposal on something that has been avoided
twice and just recently turned down, though, is a good way to get the
whole proposal rejected.

ChrisA



More information about the Python-list mailing list