[Python-ideas] Mitigating 'self.' Method Pollution

Chris Angelico rosuav at gmail.com
Sat Jul 11 13:01:32 CEST 2015


On Sat, Jul 11, 2015 at 8:52 PM, Andrew Barnert <abarnert at yahoo.com> wrote:
> But that doesn't give me what I want. The whole point is to continue to use the existing default LEGB rules for lookup (which is much more common), but to mark global assignments (where you want to differ from the default of local assignments) on the assignment statement itself, instead of function-wide. Using a different namespace obviously fails at the former, so it's like using a sledgehammer as a flyswatter.
>

Oh, I see what you mean. My apologies, I thought you wanted adornment
on all usage.

There had at one point been a proposal to allow "global NAME = EXPR"
to mean both "global NAME" and "NAME = EXPR", but I don't know that it
ever took off. What you can do, though, is repeat the global
declaration on every assignment:

def func(x):
    if not _cached:
        global _cached; _cached = expensive()
    _cached[x] += 1
    return _cached[x]

Given that there'll often be just the one such assignment anyway (as
in this example), it won't be a big problem. This is perfectly legal,
although it's worth noting that it does trigger a SyntaxWarning (name
used prior to global declaration).

It's not perfect, but it does allow you to put the word "global" right
next to the assignment.

ChrisA


More information about the Python-ideas mailing list