Inserting class namespace into method scope

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Nov 20 15:59:53 CET 2010


I find myself having need of a class where the class scope is included in 
the scope of methods in the class. A simple example from Python 3.1:

x = "outside"

class Magic:
    x = "inside"
    def method(self):
        return x


I would like Magic().method() to return "inside" rather than "outside".

Now, I understand why this is not Python's usual behaviour, and I agree 
with those reasons -- this is NOT a complaint that Python's normal 
behaviour is to exclude the class namespace from the method's scope.

I also understand that the usual way of getting this would be to return 
self.x or self.__class__.x from method, instead of x. Again, normally I 
would do this.

But in this specific case I have reasons for wanting to avoid both of the 
normal behaviours. Do not judge me, please accept that I have a good 
reason for wanting this, or at least allow me to shoot myself in the foot 
this way *wink*. In Python 3, is there some way to get this unusual 
behaviour?



-- 
Steven



More information about the Python-list mailing list