简体   繁体   English

跨脚本共享类变量吗?

[英]Are class variables shared across scripts?

I'm working on a set of Python projects with a lot of shared back-end functionality. 我正在处理一组Python项目,这些项目具有许多共享的后端功能。 To avoid code duplication, I've put this shared functionality into modules. 为避免代码重复,我已将此共享功能放入模块中。

One such module is an event system. 一个这样的模块是事件系统。 I want the event system to be global across a single project, so I defined an EventDispatcher class with class-level variables and methods: 我希望事件系统在单个项目中是全局的,因此我定义了一个具有类级变量和方法的EventDispatcher类:

event_name = str
event_data = Any
listener_callback = Callable[[event_name, event_data], None]

class EventDispatcher:
    # event name, List<event_callback>
    _listeners: Dict[event_name, Set[listener_callback]] = {}

    @classmethod
    def register_listener(cls, event: event_name, listener: listener_callback) -> None:
        # get the existing list of listeners for this event and append the new listener to it
        listener_callbacks: Set[listener_callback] = cls._listeners.get(event, set())
        listener_callbacks.add(listener)

        # put the listener list back in the map
        cls._listeners[event] = listener_callbacks

    #other listener methods follow

Because everything is class-level, I should be able to call EventDispatcher.register_listener in any class in my project, and all of the registered listeners should be added to the same list. 因为所有内容都是类级别的,所以我应该能够在项目的任何类中调用EventDispatcher.register_listener ,并且所有已注册的侦听器都应添加到同一列表中。

My concern is the other projects. 我关心的是其他项目。 Because of the amount of shared functionality, I'm running all projects from the same virtual environment. 由于共享功能的数量众多,因此我正在同一虚拟环境中运行所有项目。 Will this cause EventDispatcher and co. 这会导致EventDispatcher和co。 to be shared across all code in the virtual environment, so events registered in one project can be fired from another, or will each project get its own copy? 可以在虚拟环境中的所有代码之间共享,因此可以从另一个项目中触发在一个项目中注册的事件,或者每个项目将获得自己的副本?

As a followup question, if the shared virtual environment does cause EventDispatcher 's class variable to be shared across every project in the virtual environment, will giving each project a separate virtual environment produce the behavior I actually want? 作为后续问题,如果共享虚拟环境确实导致EventDispatcher的类变量在虚拟环境中的每个项目之间共享,那么给每个项目一个单独的虚拟环境是否会产生我真正想要的行为?

No. As long as your programs are in different files and you aren't importing a file containing the EventDispatcher class, it will not be shared in any way. 不会。只要您的程序位于不同的文件中,并且您不导入包含EventDispatcher类的文件,就不会以任何方式共享该文件。


A virtual environment will only share python version and installed packages. 虚拟环境将仅共享python版本和已安装的软件包。

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

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