Skip to content

Instantly share code, notes, and snippets.

@pauleveritt
Created August 4, 2021 08:21
Show Gist options
  • Save pauleveritt/524a3e25ee41302801521f167d94dc5a to your computer and use it in GitHub Desktop.
Save pauleveritt/524a3e25ee41302801521f167d94dc5a to your computer and use it in GitHub Desktop.
Broken example of a protocol registry
"""A broken attempt at a Protocol-based registry.
I have a system with replaceable implementations. A ``Heading``
might be asked for on a page, but which one you get depends
on some criteria.
mypy doesn't seem to like using Protocols at runtime. This
small module has 7 errors.
"""
from dataclasses import dataclass
from typing import Protocol, TypeVar
class Heading(Protocol):
full_name: str
@dataclass()
class DataclassHeading:
full_name: str = "Dataclass Heading"
class PlainClassHeading:
full_name: str
def __init__(self, full_name: str = "Plain Class Heading"):
self.full_name = full_name
# Problems begin. Is ``TypeVar`` even the right concept?
T = TypeVar("T")
#
implementations: dict[Protocol[T], T] = dict(
Heading=[DataclassHeading, PlainClassHeading],
)
def construct(protocol: Protocol[T], choice: int) -> T:
target = implementations[protocol][choice]
return target()
dh = construct(Heading, 0)
pch = construct(Heading, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment