scope of generators, class variables, resulting in global na
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Feb 27 21:44:17 EST 2010
On Sat, 27 Feb 2010 15:57:15 -0800, dontspamleo wrote:
> I think a big part of the problem is that the scoping rules in Python
> are inconsistent because classes are a different kind of object. An
> example helps:
[...]
> But this doesn't work...
> class C:
> x = 1
> def f(self,y): return x + y
>
> ...although what was probably meant was this, which does work...
> class C:
> x = 1
> def f(self,y): return self.x + y
Yes, this is a deliberate design choice. See below.
> ...and really means this...
> class C:
> x = 1
> def f(self,y): return T.x + y
I don't understand what T is. Did you mean C?
If so, you are wrong. self.x is not the same as <class>.x due to
inheritance rules. Consider one example:
>>> class A:
... x = 1
... def __init__(self, x=None):
... if x is not None:
... self.x = x
...
>>> class B(A):
... def f(self, y): return self.x + y
...
>>> class C(A):
... def f(self, y): return C.x + y
...
>>>
>>> B(5).f(10)
15
>>> C(5).f(10)
11
I have no doubt that there will be other examples involving multiple
inheritance, but I trust I've made my point.
> I argue that it is more consistent to have the scope for classes be
> consistent with the scope of everything else, which makes the early/
> late binding point mute.
Yes, it would be more consistent, but less useful. Apart from methods
themselves, using class attributes is a relatively rare thing to do, but
using global level names inside methods is very common.
> I know this is a major change, that it would break existing code, etc.
> It would have been better to talk about these things before py3k. Still:
>
> 1. Has this been discussed before?
Yes.
> 1. What would this suggestion break?
Nearly all existing code using classes, which is nearly everything.
> 2. What are the advantages of making the scope of class variables
> different? Maybe is it just a historical trait?
See the discussion in the PEP for introducing nested scopes in the first
place:
http://www.python.org/dev/peps/pep-0227/
--
Steven
More information about the Python-list
mailing list