[Python-ideas] Fixing class scope brainstorm
Paul Moore
p.f.moore at gmail.com
Tue Mar 27 12:52:18 EDT 2018
On 27 March 2018 at 16:51, Joao S. O. Bueno <jsbueno at python.org.br> wrote:
> Well, there is an idiom to "keep everything as is", and work around
> the current limitations:
>
> class A:
> def b():
> x = 1
> d = [i + x for i in range(2)]
> return locals()
> locals().update(b())
> del b
>
> Maybe if we could find a syntactic sugar for this idiom
> (with an abuse of the `with` keyword, for example), people could be happy,
> with class bodies working by default as they are now, and enabling the
> reuse of defined members by using the special syntax -
>
> class A:
> with class:
> x = 1
> d = [i + x for in range(2)]
I'd actually like to see some real world use cases to get a feel for
whether this is even worth worrying about. (I'm not saying it isn't,
just that it's hard to get a feel for the importance based on
artificial examples).
BTW, for an alternative workaround that avoids nested scopes altogether:
>>> import operator
>>> from functools import partial
>>> class C:
... x = 1
... d = list(map(partial(operator.add, x), range(2)))
...
>>> c = C()
>>> c.d
[1, 2]
No, I'm not suggesting that's clearer - but it does (at least in my
mind) make it more obvious that the problem is with comprehensions,
not with class scopes.
Paul
More information about the Python-ideas
mailing list