How to maintain lists and dictionaries between function calls in Python?

user46646 picture user46646 · Jan 7, 2009 · Viewed 11k times · Source

I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls

Suppose the dic is :

a = {'a':1,'b':2,'c':3}

At first call,say,I changed a[a] to 100 Dict becomes a = {'a':100,'b':2,'c':3}

At another call,i changed a[b] to 200 I want that dic to be a = {'a':100,'b':200,'c':3}

But in my code a[a] doesn't remain 100.It changes to initial value 1.

I need an answer ASAP....I m already late...Please help me friends...

Answer

S.Lott picture S.Lott · Jan 7, 2009

You might be talking about a callable object.

class MyFunction( object ):
    def __init__( self ):
        self.rememberThis= dict()
    def __call__( self, arg1, arg2 ):
        # do something
        rememberThis['a'] = arg1
        return someValue

myFunction= MyFunction()

From then on, use myFunction as a simple function. You can access the rememberThis dictionary using myFunction.rememberThis.