eWizardII
eWizardII

Reputation: 1936

Python Global Variable: sharing between function class then function

I'm trying to get the following global variable storage_i to be accessible to the lvl1 function, I have been able to pass it to other functions inside of the class birdofprey but I can't get it outside of that framework. I have looked around at using global variables between functions, etc, and I have also seen global var usage discouraged. But, basically I am trying to have the value of storage_i summed up from all the threads. So if that could be done without a global variable that would also be great. Any help would be appreciated.

The Code: https://github.com/eWizardII/homobabel/blob/master/Experimental/demo_async_falcon.py

Upvotes: 0

Views: 2166

Answers (2)

Shiv Deepak
Shiv Deepak

Reputation: 3116

If you want to access storage_i under lvl1() then use:

birdofprey.storage_i

Well storage_i is not a global variable, its a class attribute.

Upvotes: 0

Dan Breslau
Dan Breslau

Reputation: 11522

Replace this:

global storage_i
storage_i = i 

With this:

birdofprey.storage_i = i

You also have a typo at line 75:

storage_ii = stroage_i + storage_ii

(stroage_i was intended to be storage_i)

This line should actually be:

storage_ii =  birdofprey.storage_i + storage_ii

EDIT: Also, without having looked closely at it, your use of a class attribute (storage_i) looks like it's susceptible to race conditions. Consider using mutexes to guard accesses to that attribute. I think you also need to wait for the threads to finish executing before you can access the values.

But I'm not sure if a global (or class attribute) is really what you want. I think what you really want is a thread-local variable that you can access after the thread has finished (see the Thread.join method.) If I'm reading that correctly, then forget what I wrote above about mutexes. Instead, set the storage_i attribute as self.storage_i (creating a separate instance for each thread.) Then in the for loop where you're summing the values, access the value as urlv.storage_i. Again, it looks like it's important that you perform a join on each thread before you try to access its values.

That's all the help I can offer for now; perhaps tomorrow morning (my time) I can check in again.

Upvotes: 1

Related Questions