[Python-ideas] global and nonlocal with atributes
Nick Coghlan
ncoghlan at gmail.com
Sun May 5 13:39:50 CEST 2013
On Sun, May 5, 2013 at 9:32 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sun, May 5, 2013 at 9:10 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> But the OP's proposal is specifically to allow the global and nonlocal
>> keywords to appear in places where currently expressions can appear, as well
>> as still appearing as statements, which implies that they behave almost but
>> not quite like objects without actually being objects. That's the sort of
>> nonsense that you get in PHP, where there are things that look like
>> functions or operators, like list() and (int), but are actually magic
>> handled by the parser.
>
> Fair enough. And I absolutely agree about the PHP mess, that's not
> something to desire by any means.
>
> Maybe my modified suggestion has an alternative use, though. Is there
> value in having a token that refers to the current module? Every
> language has a way for class methods/instance methods/whatever you
> call them/etc to reference the current object instance, even if
> attribute lookup is implicit - eg C++ with 'this':
>
> foo &foo::do_something()
> {
> abcd += 3;
> return *this;
> }
>
> Needing to reference your own module isn't common, but it would allow
> you to look up your own constants via calculated names, for instance,
> so maybe there's value in it. Or maybe not, I dunno.
It's easy to do already if you want it:
import sys
thismod = sys.modules[__name__]
And yes, after doing that at the module level, you can then use
"thismod.x" instead of "global x; x" or "globals()['x']"
In general though, wanting to do this kind of thing is a sign that you
have a class or closure waiting to be defined somewhere in your code.
Some things become painful because they indicate a structural problem
in the affected code, and this is one of those cases.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list