| 1 |
_ATTR_EXCEPTIONS = frozenset(( |
| 2 |
"__args__", |
| 3 |
"__class__", |
| 4 |
"__copy__", |
| 5 |
"__deepcopy__", |
| 6 |
"__mro_entries__", |
| 7 |
"__origin__", |
| 8 |
"__parameters__", |
| 9 |
"__reduce__", |
| 10 |
"__reduce_ex__", |
| 11 |
"__typing_unpacked_tuple_args__", |
| 12 |
"__unpacked__", |
| 13 |
)) |
| 14 |
|
| 15 |
class GenericAlias: |
| 16 |
|
| 17 |
__slots__ = ("__weakref__", "_origin", "_args", "_parameters", "_hash", "__unpacked__") |
| 18 |
|
| 19 |
def __new__(cls, origin, args): |
| 20 |
result = super(GenericAlias, cls).__new__(cls) |
| 21 |
if not isinstance(args, tuple): |
| 22 |
args = (args, ) |
| 23 |
result._origin = origin |
| 24 |
result._args = args |
| 25 |
result._parameters = _collect_parameters(args) |
| 26 |
result.__unpacked__ = False |
| 27 |
return result |
| 28 |
|
| 29 |
@property |
| 30 |
def __origin__(self): |
| 31 |
return object.__getattribute__(self, "_origin") |
| 32 |
|
| 33 |
@property |
| 34 |
def __args__(self): |
| 35 |
return object.__getattribute__(self, "_args") |
| 36 |
|
| 37 |
@property |
| 38 |
def __parameters__(self): |
| 39 |
return object.__getattribute__(self, "_parameters") |
| 40 |
|
| 41 |
def __call__(self, *args, **kwargs): |
| 42 |
result = self.__origin__(*args, **kwargs) |
| 43 |
try: |
| 44 |
result.__orig_class__ = self |
| 45 |
except (AttributeError, TypeError): |
| 46 |
pass |
| 47 |
return result |
| 48 |
|
| 49 |
def __mro_entries__(self, orig_bases): |
| 50 |
return (self.__origin__, ) |
| 51 |
|
| 52 |
def __getattribute__(self, name): |
| 53 |
if name not in _ATTR_EXCEPTIONS: |
| 54 |
return getattr(self.__origin__, name) |
| 55 |
return object.__getattribute__(self, name) |
| 56 |
|
| 57 |
def __repr__(self): |
| 58 |
inner = ', '.join([_repr_item(x) for x in self.__args__]) |
| 59 |
if len(self.__args__) == 0: |
| 60 |
inner = "()" |
| 61 |
star = '*' if self.__unpacked__ else '' |
| 62 |
return f"{star}{_repr_item(self.__origin__)}[{inner}]" |
| 63 |
|
| 64 |
def __eq__(self, other): |
| 65 |
if not isinstance(other, GenericAlias): |
| 66 |
return NotImplemented |
| 67 |
return (self.__origin__ == other.__origin__ and |
| 68 |
self.__args__ == other.__args__ and |
| 69 |
self.__unpacked__ == other.__unpacked__) |
| 70 |
|
| 71 |
def __getitem__(self, items): |
| 72 |
if not isinstance(items, tuple): |
| 73 |
items = (items, ) |
| 74 |
params = self.__parameters__ |
| 75 |
args = self.__args__ |
| 76 |
newargs = subs_parameters(self, args, params, items) |
| 77 |
res = GenericAlias(self.__origin__, tuple(newargs)) |
| 78 |
if self.__unpacked__: |
| 79 |
res.__unpacked__ = True |
| 80 |
return res |
| 81 |
|
| 82 |
def __hash__(self): |
| 83 |
return hash(self.__origin__) ^ hash(self.__args__) |
| 84 |
|
| 85 |
def __dir__(self): |
| 86 |
cls = type(self) |
| 87 |
dir_origin = set(dir(self.__origin__)) |
| 88 |
return sorted(_ATTR_EXCEPTIONS | dir_origin) |
| 89 |
|
| 90 |
def __subclasscheck__(self, other): |
| 91 |
raise TypeError("issubclass() argument 2 cannot be a parameterized generic") |
| 92 |
|
| 93 |
def __instancecheck__(self, other): |
| 94 |
raise TypeError("isinstance() argument 2 cannot be a parameterized generic") |
| 95 |
|
| 96 |
def __reduce__(self): |
| 97 |
if self.__unpacked__: |
| 98 |
orig = GenericAlias(self.__origin__, self.__args__) |
| 99 |
return (_make_starred, (orig, )) |
| 100 |
return (type(self), (self.__origin__, self.__args__)) |
| 101 |
|
| 102 |
def __or__(self, other): |
| 103 |
return _create_union(self, other) |
| 104 |
|
| 105 |
def __ror__(self, other): |
| 106 |
return _create_union(other, self) |
| 107 |
|
| 108 |
def __iter__(self): |
| 109 |
yield _make_starred(self) |
| 110 |
|
| 111 |
@property |
| 112 |
def __typing_unpacked_tuple_args__(self): |
| 113 |
if self.__unpacked__ and self.__origin__ is tuple: |
| 114 |
return self.__args__ |
| 115 |
return None |
| 116 |
|
| 117 |
|
| 118 |
def _make_starred(ga): |
| 119 |
res = GenericAlias(ga.__origin__, ga.__args__) |
| 120 |
res.__unpacked__ = True |
| 121 |
return res |
| 122 |
|
| 123 |
|
| 124 |
def _repr_item(it): |
| 125 |
import typing |
| 126 |
if it == Ellipsis: |
| 127 |
return "..." |
| 128 |
if isinstance(it, GenericAlias): |
| 129 |
return repr(it) |
| 130 |
if isinstance(it, typing._GenericAlias): |
| 131 |
return repr(it) |
| 132 |
try: |
| 133 |
qualname = getattr(it, "__qualname__") |
| 134 |
module = getattr(it, "__module__") |
| 135 |
if module == "builtins": |
| 136 |
return qualname |
| 137 |
return f"{module}.{qualname}" |
| 138 |
except AttributeError: |
| 139 |
return repr(it) |
| 140 |
|
| 141 |
def _repr_item_union(it): |
| 142 |
if it is type(None): |
| 143 |
return "None" |
| 144 |
return _repr_item(it) |
| 145 |
|
| 146 |
def _is_typevar(v): |
| 147 |
t = type(v) |
| 148 |
return t.__name__ == "TypeVar" and t.__module__ == "typing" |
| 149 |
|
| 150 |
def _collect_parameters(args): |
| 151 |
"""Collect all type variables and parameter specifications in args |
| 152 |
in order of first appearance (lexicographic order). |
| 153 |
|
| 154 |
For example:: |
| 155 |
|
| 156 |
>>> P = ParamSpec('P') |
| 157 |
>>> T = TypeVar('T') |
| 158 |
>>> _collect_parameters((T, Callable[P, T])) |
| 159 |
(~T, ~P) |
| 160 |
""" |
| 161 |
|
| 162 |
parameters = [] |
| 163 |
for t in args: |
| 164 |
if isinstance(t, type): |
| 165 |
|
| 166 |
pass |
| 167 |
elif isinstance(t, tuple): |
| 168 |
|
| 169 |
|
| 170 |
for x in t: |
| 171 |
for collected in _collect_parameters([x]): |
| 172 |
if collected not in parameters: |
| 173 |
parameters.append(collected) |
| 174 |
elif hasattr(t, '__typing_subst__'): |
| 175 |
if t not in parameters: |
| 176 |
parameters.append(t) |
| 177 |
else: |
| 178 |
for x in getattr(t, '__parameters__', ()): |
| 179 |
if x not in parameters: |
| 180 |
parameters.append(x) |
| 181 |
return tuple(parameters) |
| 182 |
|
| 183 |
def subs_tvars(obj, params, argitems): |
| 184 |
"""If obj is a generic alias, substitute type variables params with |
| 185 |
substitutions argitems. For example, if obj is list[T], params is (T, S), |
| 186 |
and argitems is (str, int), return list[str]. If obj doesn't have a |
| 187 |
__parameters__ attribute or that's not a non-empty tuple, return a new |
| 188 |
reference to obj. """ |
| 189 |
from typing import TypeVarTuple |
| 190 |
subparams = getattr(obj, "__parameters__", ()) |
| 191 |
if not subparams or not isinstance(subparams, tuple): |
| 192 |
return obj |
| 193 |
nparams = len(params) |
| 194 |
nsubparams = len(subparams) |
| 195 |
subargs = [] |
| 196 |
for param in subparams: |
| 197 |
try: |
| 198 |
arg = argitems[params.index(param)] |
| 199 |
except ValueError: |
| 200 |
arg = param |
| 201 |
if isinstance(param, TypeVarTuple): |
| 202 |
subargs.extend(arg) |
| 203 |
else: |
| 204 |
subargs.append(arg) |
| 205 |
return obj[tuple(subargs)] |
| 206 |
|
| 207 |
def subs_parameters(self, args, params, items): |
| 208 |
from typing import _is_unpacked_typevartuple, _unpack_args |
| 209 |
nparams = len(params) |
| 210 |
if nparams == 0: |
| 211 |
raise TypeError(f"{self!r} is not a generic class") |
| 212 |
items = _unpack_args(items) |
| 213 |
for param in params: |
| 214 |
prepare = getattr(param, '__typing_prepare_subst__', None) |
| 215 |
if prepare is not None: |
| 216 |
items = prepare(self, items) |
| 217 |
nitems = len(items) |
| 218 |
if nparams != nitems: |
| 219 |
direction = 'many' if nitems > nparams else 'few' |
| 220 |
raise TypeError(f"Too {direction} arguments for {self}; actual {nitems}, expected {nparams}") |
| 221 |
newargs = [] |
| 222 |
for i, old_arg in enumerate(args): |
| 223 |
if isinstance(old_arg, type): |
| 224 |
newargs.append(old_arg) |
| 225 |
continue |
| 226 |
unpack = _is_unpacked_typevartuple(old_arg) |
| 227 |
meth = getattr(old_arg, '__typing_subst__', None) |
| 228 |
if meth is not None: |
| 229 |
iparam = params.index(old_arg) |
| 230 |
arg = meth(items[iparam]) |
| 231 |
else: |
| 232 |
arg = subs_tvars(old_arg, params, items) |
| 233 |
if unpack: |
| 234 |
newargs.extend(arg) |
| 235 |
else: |
| 236 |
newargs.append(arg) |
| 237 |
|
| 238 |
return newargs |
| 239 |
|
| 240 |
class UnionType: |
| 241 |
""" |
| 242 |
Represent a PEP 604 union type |
| 243 |
|
| 244 |
E.g. for int | str |
| 245 |
""" |
| 246 |
|
| 247 |
__slots__ = ("__weakref__", "_args", "__parameters__") |
| 248 |
|
| 249 |
def __init__(self, args): |
| 250 |
|
| 251 |
res = [] |
| 252 |
todo = list(args) |
| 253 |
def add_recurse(arg): |
| 254 |
if arg is None: |
| 255 |
arg = type(None) |
| 256 |
if isinstance(arg, UnionType): |
| 257 |
for a in arg.__args__: |
| 258 |
add_recurse(a) |
| 259 |
elif arg not in res: |
| 260 |
res.append(arg) |
| 261 |
for a in args: |
| 262 |
add_recurse(a) |
| 263 |
self._args = tuple(res) |
| 264 |
self.__parameters__ = _collect_parameters(args) |
| 265 |
|
| 266 |
@property |
| 267 |
def __args__(self): |
| 268 |
return object.__getattribute__(self, "_args") |
| 269 |
|
| 270 |
def __eq__(self, other): |
| 271 |
if not isinstance(other, UnionType): |
| 272 |
return NotImplemented |
| 273 |
return set(self.__args__) == set(other.__args__) |
| 274 |
|
| 275 |
def __hash__(self): |
| 276 |
return hash(frozenset(self.__args__)) |
| 277 |
|
| 278 |
def __subclasscheck__(self, other): |
| 279 |
for cls in self.__args__: |
| 280 |
if isinstance(cls, GenericAlias): |
| 281 |
raise TypeError("issubclass() argument 2 cannot contain a parameterized generic") |
| 282 |
for cls in self.__args__: |
| 283 |
if cls is None: |
| 284 |
if other is type(None): |
| 285 |
return True |
| 286 |
if issubclass(other, cls): |
| 287 |
return True |
| 288 |
return False |
| 289 |
|
| 290 |
def __instancecheck__(self, instance): |
| 291 |
for cls in self.__args__: |
| 292 |
if isinstance(cls, GenericAlias): |
| 293 |
raise TypeError("isinstance() argument 2 cannot contain a parameterized generic") |
| 294 |
for cls in self.__args__: |
| 295 |
if cls is None: |
| 296 |
if instance is None: |
| 297 |
return True |
| 298 |
elif isinstance(instance, cls): |
| 299 |
return True |
| 300 |
return False |
| 301 |
|
| 302 |
def __repr__(self): |
| 303 |
ret = " | ".join([_repr_item_union(x) for x in self.__args__]) |
| 304 |
return ret |
| 305 |
|
| 306 |
def __or__(self, other): |
| 307 |
return _create_union(self, other) |
| 308 |
|
| 309 |
def __ror__(self, other): |
| 310 |
return _create_union(other, self) |
| 311 |
|
| 312 |
def __getitem__(self, items): |
| 313 |
if not isinstance(items, tuple): |
| 314 |
items = (items, ) |
| 315 |
params = self.__parameters__ |
| 316 |
args = self.__args__ |
| 317 |
newargs = subs_parameters(self, args, params, items) |
| 318 |
if len(newargs) == 0: |
| 319 |
return UnionType(()) |
| 320 |
curr = newargs[0] |
| 321 |
for i in range(1, len(newargs)): |
| 322 |
curr |= newargs[i] |
| 323 |
return curr |
| 324 |
|
| 325 |
def _unionable(obj): |
| 326 |
return obj is None or isinstance(obj, (type, UnionType, GenericAlias)) |
| 327 |
|
| 328 |
def _create_union(self, other): |
| 329 |
if _unionable(self) and _unionable(other): |
| 330 |
if self == other: |
| 331 |
return self |
| 332 |
return UnionType((self, other)) |
| 333 |
return NotImplemented |