Need help with Python scoping rules
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Aug 26 11:55:08 EDT 2009
On Wed, 26 Aug 2009 14:09:57 +0000, kj wrote:
>>1. One of the key aspects of Python's design is that attributes must be
>>accessed explicitly with dot notation. Accessing class scopes from
>>nested functions would (seemingly) allow access to class attributes
>>without the dotted notation. Therefore it is not allowed.
>
> It would be trivial to define a keyword (e.g. this, or if you prefer,
> __this__), valid only within a class statement, and that the interpreter
> would recognize as "the current class", even before this class is full
> defined.
Python doesn't treat the addition of new keywords, and the corresponding
breakage of code which used that word as a normal name, as "trivial" --
the Python dev team takes their responsibilities to not casually break
people's code seriously. That pretty much rules out "this", although it
would allow "__this__".
However, what's your use-case?
class Demo(object):
def f(n):
return n+1
x = f(10)
is a poorly written class, because the user will expect to do this:
instance = Demo()
assert instance.c == 11 # suceeds
instance.f(10) == 11 # fails
Since the function f doesn't refer to a Demo instance, or the Demo class,
why do you put it inside the Demo class? It doesn't belong there, it
belongs in the global (module) scope. Move it out, and your problem goes
away.
The only use-case I can think of for __this__ is the following:
class Example(object):
@staticmethod
def rec(n):
if n < 2: return "x"
return "x" + __this__.rec(n/2)
Example.rec(15)
but again, why include rec() in the class if it doesn't actually have
anything to do with the class or the instance? Or why make it a
staticmethod? Just make it a class method:
class Example(object):
@classmethod
def rec(cls, n):
if n < 2: return "x"
return "x" + cls.rec(n/2)
--
Steven
More information about the Python-list
mailing list