Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created January 22, 2026 17:39
Show Gist options
  • Select an option

  • Save mypy-play/61ec65a894e2259d4b3a0e65ef31c33c to your computer and use it in GitHub Desktop.

Select an option

Save mypy-play/61ec65a894e2259d4b3a0e65ef31c33c to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from typing import ClassVar, Final, Self, Any
class Interface:
# Every subclass has a _name attribute (set by __init_subclass__)
_name: ClassVar[Final[str]]
# Registry of subclasses
_iftypes: ClassVar[Final[dict[str, type[Self]]]] = {}
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
name = cls.__name__.lower()
cls._name = name
cls._iftypes[name] = cls
def __init__(self, ifname: str) -> None:
self._ifname = ifname
@classmethod
def from_registry(cls, name: str, kind: str) -> Self:
#ifcls: type[Self] | None = cls._iftypes.get(kind)
ifcls = cls._iftypes.get(kind)
if ifcls is None:
raise ValueError()
return ifcls(name)
class Bond(Interface):
pass
class Bridge(Interface):
pass
class VLAN(Interface):
pass
for kind, ifcls in Interface._iftypes.items():
print(f'{kind}: {ifcls.__name__}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment