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

2024-06-16 12:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道在python中使用threadlocal是可能的,但是由于某些原因,我无法找到实现这一点的确切语法。我有下面的示例代码来测试这一点,但这不起作用-

模块1.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;

模数2.py

^{pr2}$

共享数据应该只对调用这些函数的线程可用,而不是对系统中的所有线程可用。一个例子是web应用程序中的请求id。在


Tags: 模块of代码pyimport示例localdef
2条回答

在模块1中,定义一个全局变量threading.local

模块1

import threading

shared = threading.local()

def print_value():
    print shared.name

模块2

^{pr2}$

如果它在同一个进程中,为什么不使用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

现在只需导入Bucket并绑定一些数据

^{pr2}$

相关问题 更多 >