Twice bound method
carlosjosepita at gmail.com
Sat Aug 27 18:54:10 CEST 2005
I want to instrumentate a class with a number of getter/setters.
Each pair of getter/setter must keep it's own state gsState but also
access to the state iState of instances of the instrumentated class.
def __init__(gsInstance, gsState):
def get(gsInstance, iInstance, attr):
def set(gsInstance, iInstance, attr, value):
def __init__(iInstance, iState):
getterSetter = GetterSetter(gsState1)
Instrumentated.getter1 = getterSetter.get
Instrumentated.setter1 = getterSetter.set
getterSetter = GetterSetter(gsState2)
Instrumentated.getter2 = getterSetter.get
Instrumentated.setter2 = getterSetter.set
instrumentated = Instrumentated(...)
At first sight I thought that the above would work fine
as getterSetter.get would bind the getter to the GetterSetter
instance and then instrumented.getter1 would bind the already
bound getter to the Instrumentated instance, so at the end
an invocation like instrumentated.getter1("x") would be calling the
original getter passing a GetterInstance as first implicit
argument, an Instrumented instance as a second one and "x"
as the third -explicit- one. Well, the fact is that the getter
is only bound to the last instance, there are no nested bindings.
Another solution could come from the use of function nested
lexical scopes and closures, with a factory function which
takes the gsState as argument and produces a getter (or setter)
function taking an iState as first argument and the attribute as
second one. Then the class can be instrumentated with the generated
getter (or setter) which keeps the gsState captured within its closure.
def getter(iState, attr):
Instrumentated.getter1 = getterGen(gsState1)
Instrumentated.getter2 = getterGen(gsState2)
Do you know of another -elegant- solution for the above problem?
Is there any way to get the nested method binding behaviour that
the first failed attempt required?
Thank you in advance.
More information about the Python-list