Remembering the context

Jean-Michel Pichavant jeanmichel at sequans.com
Thu Apr 29 05:02:24 EDT 2010


GZ wrote:
> Hi All,
>
> I am looking at the following code:
>
> def fn():
>
>     def inner(x):
>          return tbl[x]
>
>     tbl={1:'A', 2:'B'}
>     f1 = inner   # I want to make a frozen copy of the values of tbl
> in f1
>     tbl={1:'C', 2:'D'}
>     f2 = inner
>    return (f1,f2)
>
> f1,f2 = fn()
> f1(1)  # output C
> f2(1) # output C
>
> What I want is for f1 to make a frozen copy of tbl at the time f1 is
> made and f2 to make another frozen copy of tbl at the time f2 is made.
> In other words, I want f1(1)=='A' and f2(1)=='C'.
>   

something like

def makeInner(a_tbl):
    def inner(x):
        return a_tbl[x]
    return inner

def fn():
    tbl = {1:'A', 2:'B'}
    f1 = makeInner(tbl)
    tbl = {1:'C', 2:'D'}
    f2 = makeInner(tbl)
    return f1,f2

f1,f2 = fn()

In [4]: print f1(1)
A

In [5]: print f2(1)
C

JM

PS : smelling code anyway :o)



More information about the Python-list mailing list