2008-06-18

What are the ways at getting/setting a cell variable?

I have an idea brewing in my head, but it hinges on closures and preventing access to cell variables. What are the different ways on can either read or write to a cell variable from outside the closure?

Reading is pretty straightforward (I will be using Python 3.0 names): ``fxn.__func__.__closure__[0].cell_contents`` gives you direct access to the value of a cell variable. As for writing, that takes more effort:


def innocent():
x = 0
class Foo:
def get(self):
return x
return Foo

cls = innocent()

ins = cls()
print('x =', ins.get())

def evil(cls):
def outside():
x = 0
def set(self, value):
nonlocal x
x = value
return set
import types
func = types.FunctionType(outside().__code__, {},
name=cls.__name__ + '.set', closure=cls.get.__closure__)
cls.set = func

evil(cls)
print('Setting to 42')
ins.set(42)
print('x =', ins.get())

Can anyone think up of other ways to gain read or write access to cell variables?