【问题标题】:Is it possible to prevent reading from a frozen python dataclass?是否可以防止从冻结的 python 数据类中读取?
【发布时间】:2020-07-01 13:43:55
【问题描述】:

我有一种情况,我希望能够将冻结的dataclass 实例视为始终拥有最新数据。或者换句话说,我希望能够检测一个数据类实例是否已经调用了replace 并抛出异常。它也应该只适用于那个特定的实例,这样相同类型的其他数据类实例的创建/替换不会相互影响。

这里是一些示例代码:

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class AlwaysFreshData:
    fresh_data: str


def attempt_to_read_stale_data():
    original = AlwaysFreshData(fresh_data="fresh")
    unaffected = AlwaysFreshData(fresh_data="not affected")

    print(original.fresh_data)

    new = replace(original, fresh_data="even fresher")

    print(original.fresh_data) # I want this to trigger an exception now

    print(new.fresh_data)

这里的想法是防止 从我们的数据类对象中发生意外突变和过时读取,以防止出现错误。

可以这样做吗?通过基类还是其他方法?

编辑:这里的目的是有一种方法来强制/验证数据类的“所有权”语义,即使它只是在运行时。

这是一个有问题的常规数据类情况的具体示例。

@dataclass
class MutableData:
    my_string: str

def sneaky_modify_data(data: MutableData) -> None:
    some_side_effect(data)
    data.my_string = "something else" # Sneaky string modification

x = MutableData(my_string="hello")

sneaky_modify_data(x)

assert x.my_string == "hello" # as a caller of 'sneaky_modify_data', I don't expect that x.my_string would have changed!

这可以通过使用冻结数据类来防止!但是仍然存在可能导致潜在错误的情况,如下所示。

@dataclass(frozen=True)
class FrozenData:
    my_string: str

def modify_frozen_data(data: FrozenData) -> FrozenData:
   some_side_effect(data)
   return replace(data, my_string="something else")

x = FrozenData(my_string="hello")

y = modify_frozen_data(x)

some_other_function(x) # AHH! I probably wanted to use y here instead, since it was modified!

总之,我希望能够防止对数据进行偷偷摸摸或未知的修改,同时强制使已替换的数据失效。 这样可以防止意外使用过期数据。

这种情况对某些人来说可能很熟悉,类似于 Rust 中的所有权语义。

至于我的具体情况,我已经有大量使用这些语义的代码,除了 NamedTuple 实例。这是可行的,因为在任何实例上修改 _replace 函数都可以使实例无效。对于数据类,同样的策略并不适用,因为 dataclasses.replace 不是实例本身的函数。

【问题讨论】:

  • 看起来你真正想要的是一个非冻结的数据类,所以你可以更新fresh_data的值。
  • 这似乎是X-Y problem。您正在修改数据(使用replace),但您希望冻结数据,因此您正在创建一个新实例。同时,您不希望使用旧实例,因为它不再有效。为什么不按照@jonrsharpe 的建议让对象不被冻结?这样你就不会遇到现在试图解决的任何问题。向您解释最初的问题 X,而不是为 Y 寻求解决方案。
  • @zvone 公平地说,replace 的主要目的是用冻结的数据类调用。指出问题提示设计问题是很好的,但是 OP 的情况,或者通过谷歌找到这篇文章的任何人的情况,可能会使重新设计不可行。
  • @zvone 我已经更新了我的问题,更详细地说明了我为什么要寻找这个特定的解决方案以及为什么非冻结数据类不适合。
  • @zvone 我认为这里存在误解。 some_side_effect 不修改任何内容,它只是表示一些不更改数据的工作的一种方式。使用冻结数据类背后的想法是在不明确的情况下防止修改。但是,它仍然不能阻止“未修改”数据的使用,这可能会导致细微的、难以跟踪的错误。现在,显然这种事情可以通过更仔细和更好的代码审查来处理,但如果能够在它们导致生产中的错误之前捕捉到这种情况的发生,那就太好了。

标签: python immutability python-dataclasses


【解决方案1】:

我同意 Jon 的观点,即保持适当的数据清单和更新共享实例将是解决问题的更好方法,但如果由于某种原因这是不可能或不可行的(您应该认真检查如果它真的足够重要),有一种方法可以实现您所描述的(顺便说一句,好的模型)。不过,这将需要一些重要的代码,并且之后对您的数据类有一些限制:

from dataclasses import dataclass, replace, field
from typing import Any, ClassVar


@dataclass(frozen=True)
class AlwaysFreshData:
    #: sentinel that is used to mark stale instances
    STALE: ClassVar = object()

    fresh_data: str
    #: private staleness indicator for this instance
    _freshness: Any = field(default=None, repr=False)

    def __post_init__(self):
        """Updates a donor instance to be stale now."""

        if self._freshness is None:
            # is a fresh instance
            pass
        elif self._freshness is self.STALE:
            # this case probably leads to inconsistent data, maybe raise an error?
            print(f'Warning: Building new {type(self)} instance from stale data - '
                  f'is that really what you want?')
        elif isinstance(self._freshnes, type(self)):
            # is a fresh instance from an older, now stale instance
            object.__setattr__(self._freshness, '_instance_freshness', self.STALE)
        else:
            raise ValueError("Don't mess with private attributes!")
        object.__setattr__(self, '_instance_freshness', self)

    def __getattribute__(self, name):
        if object.__getattribute__(self, '_instance_freshness') is self.STALE:
            raise RuntimeError('Instance went stale!')
        return object.__getattribute__(self, name)

您的测试代码的行为如下:

# basic functionality
>>> original = AlwaysFreshData(fresh_data="fresh")
>>> original.fresh_data
fresh
>>> new = replace(original, fresh_data="even fresher")
>>> new.fresh_data
even_fresher

# if fresher data was used, the old instance is "disabled"
>>> original.fresh_data
Traceback (most recent call last):
  File [...] in __getattribute__
    raise RuntimeError('Instance went stale!')
RuntimeError: Instance went stale!

# defining a new, unrelated instance doesn't mess with existing ones
>>> runner_up = AlwaysFreshData(fresh_data="different freshness")
>>> runner_up.fresh_data
different freshness
>>> new.fresh_data  # still fresh
even_fresher
>>> original.fresh_data  # still stale
Traceback (most recent call last):
  File [...] in __getattribute__
    raise RuntimeError('Instance went stale!')
RuntimeError: Instance went stale!

需要注意的重要一点是,这种方法为数据类引入了一个新字段,即_freshness,它可能是手动设置的,并且会打乱整个逻辑。您可以尝试在 __post_init__ 中捕获它,但这样的事情将是让旧实例保持新鲜的有效偷偷摸摸的方法:

>>> original = AlwaysFreshData(fresh_data="fresh")
# calling replace with _freshness=None is a no-no, but we can't prohibit it
>>> new = replace(original, fresh_data="even fresher", _freshness=None)
>>> original.fresh_data
fresh
>>> new.fresh_data
even_fresher

另外,我们需要一个默认值,这意味着在它下面声明的任何字段也需要一个默认值(这还不错 - 只需声明它上面的那些字段),包括来自未来孩子的所有字段(这更多的是一个问题,并且有一个huge post关于如何处理这种情况)。

每当您使用这种模式时,您还需要一个可用的哨兵值。这还不错,但对某些人来说可能是一个奇怪的概念。

【讨论】:

  • 非常感谢您的回答!不幸的是,它似乎并没有像我期望的那样工作。在此示例中:a = AlwaysFreshData("A1") b = AlwaysFreshData("B1") print(a) # This triggers an exception, even though 'a' was not replaced 在您给出的代码示例中,创建的实例会干扰其他实例的“新鲜度”
  • 哈哈,这是一个不容错过的大事件。我会看看我是否可以更新我的帖子。
  • @SanchitUttam 我找到了一种方法。它甚至更短一些,但会带来潜在的副作用。
  • 谢谢!这确实回答了我提出的问题。不幸的是,我不能按原样使用该解决方案,因为它确实涉及引入一个默认属性,该属性在尝试从数据类继承时会引发问题(正如您在帖子中的链接中提到的那样)。尽管如此,我会将问题标记为已回答。如果你很好奇,我设法通过猴子修补dataclasses.replace 来解决我的问题。我意识到这不是一个干净的解决方案,但它比我想出的任何其他方法都要干净
  • 很高兴您找到了解决方案,感谢您的接受!
猜你喜欢
  • 2014-09-20
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2011-11-03
  • 1970-01-01
  • 2016-09-24
  • 2020-07-21
相关资源
最近更新 更多