[Python] How to make an easily instantiable derivative attribute-only protocol class?

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Protocol subclass that defines objects with attributes from an external library:

    class P(Protocol):
    val: int


    For testing purposes, I want to turn this protocol class into something I can instantiate easily. However, when I try to turn it into a dataclass, an error pops up:

    import dataclasses
    from typing import Protocol

    class P(Protocol):
    val: int

    PInst = dataclasses.dataclass(P)

    PInst(val=4) # TypeError: Protocols cannot be instantiated


    Is there an easy solution to use P to create a class that satifies its protocol and is instantiable, without redeclaring its attributes?

    Continue reading...

Compartilhe esta Página