Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 867
user46646 Avatar asked Nov 26 '22 21:11

user46646


2 Answers

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.

like image 137
S.Lott Avatar answered Nov 29 '22 13:11

S.Lott


You could use a static variable:

def foo(k, v):
  foo.a[k] = v
foo.a = {'a': 1, 'b': 2, 'c': 3}

foo('a', 100)
foo('b', 200)

print foo.a
like image 20
too much php Avatar answered Nov 29 '22 14:11

too much php