Skip to content

Freezing an attribute in __attrs_post_init__ #1412

Closed
@jacopoabramo

Description

@jacopoabramo

I have a class like this:

from attrs import define, field, validators

@define
class LightModelInfo:

    wavelength: int = field(
        validator=validators.instance_of(int),
        metadata={"description": "Wavelength in nm."},
    )
    wavecolor: str = field(
        init=False,
        metadata={"description": "Hexadecimal representation of the light color."},
    )

    def __attrs_post_init__(self) -> None:
        # this should be frozen after being computed
        self.wavecolor = wavelength_to_hex(self.wavelength)

I would like to freeze the wavecolor attribute during post initialization, or an alternative approach which allows me to compute the value of wavecolor based on wavelength and then freeze it. Is it possible?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions