Skip to content

Instantly share code, notes, and snippets.

@AndrewOwenMartin
Created November 9, 2021 14:42
Show Gist options
  • Save AndrewOwenMartin/5fe66a7fdabb6c129b200adee5931972 to your computer and use it in GitHub Desktop.
Save AndrewOwenMartin/5fe66a7fdabb6c129b200adee5931972 to your computer and use it in GitHub Desktop.
Example of Protocol class in Mypy
from typing import Any, Union, Dict
from typing_extensions import TypedDict, Protocol
class FooMeta:
meta = dict(a=1)
class BarMeta:
def __init__(self):
self.meta = dict(foo="bar")
class SupportsMeta(Protocol):
meta: Dict[str, Any]
def frobnicate(obj: SupportsMeta, key: str) -> Any:
value = obj.meta[key]
return value
def main():
foo = FooMeta()
bar = BarMeta()
bar2 = BarMeta()
print(frobnicate(foo, "a"))
print(frobnicate(bar, "foo"))
print(frobnicate(bar2, "foo"))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment