Created
November 9, 2021 14:42
-
-
Save AndrewOwenMartin/5fe66a7fdabb6c129b200adee5931972 to your computer and use it in GitHub Desktop.
Example of Protocol class in Mypy
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 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