简体   繁体   中英

Python 3.8 class variable not persistent

A class variable for a Python class does not appear to persist between packages.

I have a class "HookRegistry" that is supposed to dynamically record the functions that are annotated with the @regiser_hook method. IT does so successfully, but when I go again to find out the list of hooks registered, the list variable holding them appears to be reinitialized.

class HookRegistry(object):
    hooks = []

    def register_hook(f):
        HookRegistry.hooks.append(f)
        print("Registrering hook. There are now {} hooks registered.".format(len(HookRegistry.hooks)))
        def wrap(*args, **kwargs):
            f(*args, **kwargs)
        return wrap

    def execute_hooks(*args, **kwargs):
        for f in HookRegistry.hooks:
            f(*args, **kwargs)

Full source code can be found at https://github.com/conallprendergast/python_hook_registry_example/tree/not_working

I am running python 3.8 on arch linux

This issue is fixed by changing my code in my "hook" do_something* files. The import of

from hookregistry import HookRegistry

needs to be changed to

from .hookregistry import HookRegistry

This is no working because module do_something* doesn't executed.(we easy can check this: just add incorrect code to do_something.py

This can be fixed, add this code to hooks/__init__.py

from .do_something import *
from .do_something_else import *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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