Python: ContextManager для мутаций объектов?Python

Программы на Python
Ответить Пред. темаСлед. тема
Гость
 Python: ContextManager для мутаций объектов?

Сообщение Гость »


Я хотел бы создать шаблон кода, который позволит мне сделать что-то аналогичное следующему:

Код: Выделить всё

# Foo has getter-only properties
foo: Foo = FooRepo.get(id="foo_id")
assert foo.bar == "original_bar"

# MutableFoo is a window onto the Foo, and when it __exit__s, it persists to the repo
with foo.mutable() as mutable_foo:
mutable_foo.bar = "new_bar"

# We've updated the Foo, as well as whatever persistent version the FooRepo owns
assert foo.bar == "new_bar"
I'm not wedded to the exact code pattern. What I like about it:
  • We can pass the Foo around to lots of areas of code, and as long as mutable() isn't called, we can treat it as immutable and ignore the idea of persistence.
  • We have the ability to work transactionality into that ContextManager in a variety of ways. Outside of the ContextManager we get to treat the object as a snapshot, which will be more common and is less hairy.
  • Callers can largely ignore persistence
Challenges I see:
  • Need an elegant way of preventing creating the mutable version outside of a with block.
  • Ditto with whatever interface into Foo enables MutableFoo to do its mutation. (Can you tell I'm used to Java? Lacking inner classes with access to private members has me scratching my head a bit)
  • Need an elegant way of doing error checking. Since the persistence happens in response to exiting the context, there's potential for exceptions and those will need to be caught and handled responsibly.
Have folks built frameworks of this kind in Python? What solutions do you like?


Источник: https://stackoverflow.com/questions/781 ... -mutations
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»