Skip to content

Instantly share code, notes, and snippets.

@goabonga
Created July 27, 2025 16:32
Show Gist options
  • Select an option

  • Save goabonga/79f4c301e6bf6ad7b6f6f2f7f860828d to your computer and use it in GitHub Desktop.

Select an option

Save goabonga/79f4c301e6bf6ad7b6f6f2f7f860828d to your computer and use it in GitHub Desktop.
MyList and MyDict
from collections.abc import MutableMapping
from typing import Iterator
from .user import MyUser
TKey = str
class MyDict(MutableMapping[TKey, MyUser]):
def __init__(self) -> None:
self._store: dict[TKey, MyUser] = {}
def __getitem__(self, key: TKey) -> MyUser:
return self._store[key]
def __setitem__(self, key: TKey, value: MyUser) -> None:
if not isinstance(value, MyUser):
raise TypeError("Only MyUser instances are allowed")
self._store[key] = value
def __delitem__(self, key: TKey) -> None:
del self._store[key]
def __iter__(self) -> Iterator[TKey]:
return iter(self._store)
def __len__(self) -> int:
return len(self._store)
from typing import Iterable, overload, Union
from typing import SupportsIndex
from .user import MyUser
class MyList(list[MyUser]):
def append(self, item: MyUser) -> None:
if not isinstance(item, MyUser):
raise TypeError("Only MyUser instances are allowed")
super().append(item)
def extend(self, iterable: Iterable[MyUser]) -> None:
for item in iterable:
self.append(item)
def insert(self, index: SupportsIndex, item: MyUser) -> None:
if not isinstance(item, MyUser):
raise TypeError("Only MyUser instances are allowed")
super().insert(index, item)
@overload
def __setitem__(self, index: SupportsIndex, item: MyUser) -> None: ...
@overload
def __setitem__(self, index: slice, item: Iterable[MyUser]) -> None: ...
def __setitem__(self, index: Union[SupportsIndex, slice], item: Union[MyUser, Iterable[MyUser]]) -> None:
if isinstance(index, slice):
if not isinstance(item, Iterable) or not all(isinstance(x, MyUser) for x in item):
raise TypeError("Only MyUser instances are allowed in slice assignment")
super().__setitem__(index, item)
else:
if not isinstance(item, MyUser):
raise TypeError("Only MyUser instances are allowed")
super().__setitem__(index, item)
class MyUser:
def __init__(self, name: str) -> None:
self.name = name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment