1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Synchronize attribute changes in Python

Discussão em 'Python' iniciado por Stack, Setembro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I've subclassed a Python dict, roughly like this:

    class JSONDict(dict):
    @property
    def __json__(self):
    return json.dumps(self)

    @property
    def __path__(self):
    return os.path.join(settings.BASE_PATH, self.entity, 'settings.json')

    def __init__(self, entity, *args, **kwargs):
    dict.__init__(self)
    self.entity = entity

    try:
    os.utime(self.__path__, None)
    except OSError:
    open(self.__path__, 'a').close()

    self.__file__ = open(self.__path__, 'r+')
    self.__to_python__()

    def __enter__(self):
    return self

    def __exit__(self, exc_type, exc_value, traceback):
    self.__file__.close()

    def __to_json__(self):
    self.__file__.seek(0)
    self.__file__.write(self.__json__)
    self.__file__.flush()
    self.__file__.truncate()

    def __to_python__(self):
    if os.path.getsize(self.__path__):
    self.__file__.seek(0)
    dict.clear(self)
    dict.update(self, json.load(self.__file__))
    else:
    self.clear()

    def __getitem__(self, key):
    self.__to_python__()
    return dict.__getitem__(self, key)

    def __setitem__(self, key, value):
    dict.__setitem__(self, key, value)
    self.__to_json__()

    def update(self, data):
    dict.update(self, data)
    self.__to_json__()

    def clear(self):
    dict.clear(self)
    self.update(__default__)
    self['nar'] = self.nar


    I can use this quite fine, e.g.:

    >>> with JSONDict('entity-id') as json_info:
    ... json_info['setting_a'] = 'foo'


    However, there's an interesting problem when it comes to lists. When I modify the list directly, e.g json_info['setting_b'].append('bar'), the JSON file doesn't get updated. I was certain that overriding __setitem__ and __getitem__ would cover all item access, but clearly that's not the case. What should I override to get this work?

    UPDATE:

    Having read the first answers, I felt that this question wasn't formulated in a right way. The right question would be, how to effectively observe dict attribute changes in order to be able to update the JSON accordingly? Should it be done via proxy/descriptor objects, metaclasses, or is there a more generic way?

    Continue reading...

Compartilhe esta Página