0

I know this is possible using thread local in python but for some reason I am unable to find the exact syntax to achieve this. I have following sample code to test this but this is not working -

module1.py

import threading

def print_value():
    local = threading.local() // what should I put here? this is actually creating a new thread local instead of returning a thread local created in main() method of module2.
    print local.name;

module2.py

import module1

if __name__ == '__main__':
    local = threading.local()
    local.name = 'Shailendra'
    module1.print_value()

Edit1 - Shared data should be available to only a thread which will invoke these functions and not to all the threads in the system. One example is request id in a web application.

Shailendra
  • 319
  • 4
  • 14
  • Possible duplicate of [Python: How to make a cross-module variable?](http://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable) – Sameer Mirji Feb 19 '16 at 06:11

2 Answers2

0

In module 1, define a global variable that is a threading.local

module1

import threading

shared = threading.local()

def print_value():
    print shared.name

module2

import module1

if __name__ == '__main__':
    module1.shared.name = 'Shailendra'
    module1.print_value()
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
-1

If it's within the same process, why not use a singleton?

import functools

def singleton(cls):
    ''' Use class as singleton. '''

    cls.__new_original__ = cls.__new__

    @functools.wraps(cls.__new__)
    def singleton_new(cls, *args, **kw):
       it =  cls.__dict__.get('__it__')
       if it is not None:
           return it

       cls.__it__ = it = cls.__new_original__(cls, *args, **kw)
       it.__init_original__(*args, **kw)
       return it

   cls.__new__ = singleton_new
   cls.__init_original__ = cls.__init__
   cls.__init__ = object.__init__

   return cls

@singleton
class Bucket(object):
    pass

Now just import Bucket and bind some data to it

from mymodule import Bucket
b = Bucket()
b.name = 'bob'
b.loves_cats = True
willnx
  • 1,253
  • 1
  • 8
  • 14
  • Singleton is for storing global data. It can't be used to store information which should be available to only one thread and all the functions which this thread will invoke for a particular request. One example of such data is user information which can't be exposed as global data as it will expose user information to all other users. – Shailendra Feb 19 '16 at 07:46
  • Ahhh! I misread your intent; sounded like you wanted to share data between threads and functions (like 'g' in Flask). – willnx Feb 19 '16 at 08:49