简体   繁体   English

在python 2.x中两个不同模块中的两个函数之间共享数据

[英]Sharing data between two functions in two different modules in python 2.x

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. 我知道这可以在python中使用本地线程实现,但是由于某些原因,我无法找到实现此目的的确切语法。 I have following sample code to test this but this is not working - 我有以下示例代码对此进行测试,但这无法正常工作-

module1.py 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 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. Edit1-共享数据仅对将调用这些功能的线程可用,而不对系统中的所有线程可用。 One example is request id in a web application. 一个示例是Web应用程序中的请求ID。

In module 1, define a global variable that is a threading.local 在模块1中,定义一个全局变量,它是threading.local

module1 模块1

import threading

shared = threading.local()

def print_value():
    print shared.name

module2 模块2

import module1

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

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 现在只需导入Bucket并将一些数据绑定到其中

from mymodule import Bucket
b = Bucket()
b.name = 'bob'
b.loves_cats = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM