[Python] How can I use a decorator to flag classes as passing a certain Protocol?

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to be able to define a decorator for a class in python adding a class attribute which I can then check for in a Protocol, to be used in type checking elsewhere.

    I tried the following code:

    from dataclasses import dataclass
    from typing import Protocol, Any

    class Canine(Protocol):
    __canine__: Any

    def make_canine(cls):
    setattr(cls, "__canine__", True)
    return cls

    @make_canine
    @dataclass
    class Dog:
    name: str
    weight: float
    colour: str
    good_dog: bool = True


    @dataclass
    class Cat:
    name: str
    weight: float
    colour: str
    good_cat: bool = True


    def play_fetch(animal: Canine):
    print(f"Playing fetch with {animal}...")

    clifford = Dog('Clifford', 1000, 'Red')
    garfield = Cat('Garfield', 10, 'Orange')

    play_fetch(Dog) # I expected this to pass type checking
    play_fetch(Cat) # I expected this to fail type checking

    play_fetch(clifford) # I thought this would also pass, but I'm not sure?
    play_fetch(garfield) # I expect this to fail

    print(Dog.__canine__) # print(True)
    print(Cat.__canine__) # AttributeError


    None of the lines that I thought would pass type checking did. Can someone explain why it doesn't behave as I expected?

    Continue reading...

Compartilhe esta Página