Skip to content

Instantly share code, notes, and snippets.

@IgorZyktin
Last active August 23, 2021 11:06
Show Gist options
  • Save IgorZyktin/4ceaa8bc10e227eaaaafd87b95e59446 to your computer and use it in GitHub Desktop.
Save IgorZyktin/4ceaa8bc10e227eaaaafd87b95e59446 to your computer and use it in GitHub Desktop.
# простейший дженерик ----------------------------------------
from typing import Generic
from typing import TypeVar
T = TypeVar('T')
class Cool(Generic[T]):
def __init__(self):
self._storage = []
def put(self, something: T) -> None:
self._storage.append(something)
def pop(self) -> T:
return self._storage.pop()
array: Cool[int] = Cool()
array.put(1) # Ok
array.put('wtf') # Expected type 'int' (matched generic type 'T'), got 'str' instead
# простейший абстрактный базовый класс ---------------------
from abc import ABC
from abc import abstractmethod
class Parent(ABC):
@abstractmethod
def must_implement(self):
"""Abstract."""
class Child(Parent):
pass
c = Child() # TypeError: Can't instantiate abstract class Child with abstract method must_implement
# простейший протокол ---------------------
from typing import Protocol
class DoProtocol(Protocol):
def do(self) -> int:
pass
class SomethingInt:
def do(self) -> int:
return 1
class SomethingStr:
def do(self) -> str:
return 'sd'
def some_func(something: DoProtocol) -> None:
print(something)
some_func(SomethingInt()) # Ok
some_func(SomethingStr()) # Expected type 'DoProtocol', got 'SomethingStr' instead
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment