import builtins class GenericWrapper(builtins.type): def __init__(self, origin, _args): return super().__init__(origin, (), dict()) def __new__(self, origin, parameters): self.__origin__ = origin if not isinstance(parameters, tuple): parameters = (parameters,) self.__args__ = parameters def __class_getitem__(cls, key): raise TypeError("Cannot subscript already subscripted generic type.") return super().__new__(self, 'GenericWrapper', (origin,), {'__class_getitem__': __class_getitem__}) def __instancecheck__(self, instance): raise TypeError("Subscripted types cannot be used with class and instance checks.") def __subclasscheck__(self, subclass): return isinstance(subclass, self) def __repr__(self) -> str: reprs = [] for p in (self.__origin__,) + self.__args__: if hasattr(p, "__origin__") and hasattr(p, "__args__"): # Looks like a Proxy r = repr(p) elif p == Ellipsis: # For tuple[int, ...] r = "..." elif hasattr(p, "__qualname__") and hasattr(p, "__module__"): # Looks like a class if p.__module__ in ("builtins", "__main__"): # These don't need a module name (not sure about __main__?) r = p.__qualname__ else: r = f"{p.__module__}.{p.__qualname__}" else: # Fallback r = repr(p) reprs.append(r) origin = reprs.pop(0) if reprs: params = ", ".join(reprs) else: # Special case to replace list[] with list[()] params = "()" return f"{origin}[{params}]" def __class_getitem__(cls, key): raise TypeError("Cannot subscript already subscripted generic type.") class list(builtins.list): def __class_getitem__(cls, key): return GenericWrapper(cls, key) class type(builtins.type): def __class_getitem__(cls, key): return GenericWrapper(cls, key) class dict(builtins.dict): def __class_getitem__(cls, key): return GenericWrapper(cls, key) if __name__ == '__main__': l = list[int]((1,2,3)) l.append('t') isinstance(l, list) print(l) print(list[str]) print(list[str].__origin__) print(list[int].__args__) try: isinstance(l, list[int]) except TypeError: print("isinstance correctly errored") else: print("uh-oh") isinstance(l, builtins.type(l)) try: list[str][str] except TypeError: print("repeated class getitem denied") else: print("uh-oh") t = type('test', (), {}) print(t) print(type[list]) print(dict[str, str]) dict[str, str].fromkeys(range(10))