A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2018-February/152190.html below:

[Python-Dev] Dataclasses, frozen and __post_init__

[Python-Dev] Dataclasses, frozen and __post_init__Nick Coghlan ncoghlan at gmail.com
Tue Feb 20 08:03:25 EST 2018
On 20 February 2018 at 15:11, Steven D'Aprano <steve at pearwood.info> wrote:
> So in principle, we could have a mutable class, and a immutable one, and
> when you flick the switch, the instance.__class__ changes from mutable
> to frozen.
>
> If you don't hate this, we can think about the details needed to get
> it work in practice.

This doesn't technically require any additional changes, as you can
already do it with __post_init__:

    @dataclass
    class MyRecord:
        a: int
        b: str
        c: float

        def __post_init__(self):
            # self is still mutable here
            self.__class__ = _LockedMyRecord

    @dataclass(frozen=True)
    class _LockedMyRecord(MyRecord):
        pass

This is also the kind of runtime behaviour modification where hiding
how it's implemented is likely to create more problems than it solves,
as even though having "type(obj)" and "obj.__class__" refer to
different types is a formally supported state for instances, there are
also lots of APIs where it isn't well defined whether an attribute
lookup will use the nominal class or the true underlying type.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4