Created
February 6, 2022 15:15
-
-
Save jerry-git/da09df944a5436e6865bd10420a28227 to your computer and use it in GitHub Desktop.
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
import typing | |
import uuid | |
from dataclasses import dataclass | |
class InstanceWithId(typing.Protocol): | |
@property | |
def id(self) -> str: | |
... | |
def print_instance_id(instance: InstanceWithId) -> None: | |
print(f"Received instance with id: {instance.id}") | |
@dataclass | |
class MyDataClass: | |
id: str | |
class MyRegularClass: | |
def __init__(self) -> None: | |
self.id = str(uuid.uuid4()) | |
class MyNamedTuple(typing.NamedTuple): | |
id: str | |
class ClassWithoutId: | |
... | |
print_instance_id(MyDataClass(id="123")) | |
print_instance_id(MyRegularClass()) | |
print_instance_id(MyNamedTuple(id="abc")) | |
print_instance_id(ClassWithoutId()) # mypy gives error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment