Skip to content

Instantly share code, notes, and snippets.

@adriangb
Created February 27, 2022 23:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save adriangb/6c1a001ee7035bad5bd56df70e0cf5e6 to your computer and use it in GitHub Desktop.
template class
from typing import ClassVar, Protocol
class APIKey(Protocol): # provided by some framework
header_name: ClassVar[str]
key: str
def __init__(self, key: str) -> None: # so that framework can construct the subclass
self.key = key
class MyAPIKey(APIKey):
header_name = "foo" # user fills in the blanks or type checker complains
def endpoint(auth: MyAPIKey) -> None: # framework knows the right class to inject from the signature
assert auth.key == "123"
def framework() -> None:
# get key from request
endpoint(MyAPIKey("123")) # confusing error here due to how Protocol overrides __init__ from __init_subclass__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment