Thursday, 15 March 2012

python - Accessing a function's variable from another function -



python - Accessing a function's variable from another function -

from threading import thread import time def print_k(): while true: if main.k % 2 == 1: # ditto print(main.k, "is even.") # <-- problem here ( ignore other stuff ) time.sleep(2) def main(): k = 1 while k != 200: k += 1 print k time.sleep(0.5) if __name__ == '__main__': thread(target=print_k).start() thread(target=main).start()

in script (example only, ignore realistic functionality) trying run main(), adds 200 , prints it, , in print_k, printing main's variable, k. have exception raised, unsurprisingly, , wondering how can access separate function's variable different function (they both running @ same time, way, hence threading module.)

you can't print main's variable k. whole point of local variables they're local. doesn't matter whether they're running @ same time or not; each have own separate local environment. (in fact, if phone call main 60 times, each of 60 calls has own local environment.)

but there number of things can do.

the simplest, worst, utilize global variables instead of local variables. add together global k top of main function, add together start value k @ top level (before either thread starts), , can access same global variable within print_k.

bundling shared state , functions in class, both functions become methods can access self.k, improve solution. passing in kind of mutable "holder" both main , print_k improve solution. redesigning app around explicit message passing (e.g., on queue.queue) better.

i'll show how class:

class kcounter(object): def __init__(self): self.k = 0 def print_k(self): while true: if self.k % 2 == 1: print(self.k, "is even.") time.sleep(2) def main(self): self.k = 1 while self.k != 200: self.k += 1 print self.k time.sleep(0.5) if __name__ == '__main__': kcounter = kcounter() thread(target=kcounter.print_k).start() thread(target=kcounter.main).start()

now, because we're using self.k, attribute of kcounter instance, instead of k, local variable, both methods see same variable.

python multithreading function python-2.7 user-defined-functions

No comments:

Post a Comment