Created
February 27, 2022 23:56
-
-
Save adriangb/6c1a001ee7035bad5bd56df70e0cf5e6 to your computer and use it in GitHub Desktop.
template class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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