[Python-ideas] Mitigating 'self.' Method Pollution
abarnert at yahoo.com
Sat Jul 11 12:52:44 CEST 2015
On Jul 11, 2015, at 03:13, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Jul 11, 2015 at 8:02 PM, Andrew Barnert via Python-ideas
> <python-ideas at python.org> wrote:
>> If I were designing a new pythonesque language, I think I might well add
>> something like that for when you need to disambiguate from the default, and
>> then get rid of the global statement. In fact, if it weren't for the obvious
>> huge backward compat problems, I might even go for a suggestion to do that
>> in Python. Even for closure variables, I kind of like the look of
>> "nonlocal.x = 3", although it's not _as_ compelling as "global.x = 3" to me.
> Want it in Python? No problem. You can't have "global.x" because it's
> a keyword, but...
> globl = SimpleNamespace()
> def use_globals():
> globl.x += 1
> return globl.y
> If you want it, it's there, but I wouldn't bother with it for
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.
(I suppose you _could_ use global.const instead of const with this change, but there'd never actually be a reason to do so, unless you intentionally shadowed the global with a local and wanted to access both, and that's a silly thing to do and trivial to avoid, even in auto-generated code.)
> - including functions, which are globals just the same as
> any other. We do NOT need this kind of enforced adornment for all
Which is why I suggested it might be good only for global assignments (and nonlocal assignments), not for all names. Global assignments are much rarer than global lookups and local assignments, and marking them at the point of assignment would make it explicit that you're doing something uncommon.
If you keep your functions small enough, it's rarely a serious issue that you have to look upward to notice that the x=5 isn't creating a local variable, but I still think it might be better (again, in a new pythonesque language--I don't seriously want to change Python here) to remove the issue.
More information about the Python-ideas