[Python] How to type hint an attribute to be a dataclass?

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I want a class that encapsulates data with some meta information. The data changes during runtime. I want to safe it for evaluation. The class looks like this:

    from dataclasses import dataclass, replace, _DataclassT


    @dataclass
    class Encapsulated[P: ???]: # <- What to specify here?
    type: int
    payload: P

    def record(self) -> P:
    return replace(self.payload)



    As you can see, I have no requirements with regard to P except that is has to be a Dataclass that can be used in dataclasses.replace. For example:

    @dataclass
    class Payload:
    val: int = 0


    I tried object which fails for obvious reasons. I find _DataclassT inappropriate because of it being private. Also: It doesn't work.

    Continue reading...

Compartilhe esta Página