Parameterizes a generic class. At least, parameterizing a generic class is the *main* thing this method does. For example, for some generic class `Foo`, this is called when we do `Foo[int]` - there, with `cls=Foo` and `args=int`. However, note that this method is also called when d
(cls, args)
| 1112 | |
| 1113 | @_tp_cache |
| 1114 | def _generic_class_getitem(cls, args): |
| 1115 | """Parameterizes a generic class. |
| 1116 | |
| 1117 | At least, parameterizing a generic class is the *main* thing this method |
| 1118 | does. For example, for some generic class `Foo`, this is called when we |
| 1119 | do `Foo[int]` - there, with `cls=Foo` and `args=int`. |
| 1120 | |
| 1121 | However, note that this method is also called when defining generic |
| 1122 | classes in the first place with `class Foo(Generic[T]): ...`. |
| 1123 | """ |
| 1124 | if not isinstance(args, tuple): |
| 1125 | args = (args,) |
| 1126 | |
| 1127 | args = tuple(_type_convert(p) for p in args) |
| 1128 | is_generic_or_protocol = cls in (Generic, Protocol) |
| 1129 | |
| 1130 | if is_generic_or_protocol: |
| 1131 | # Generic and Protocol can only be subscripted with unique type variables. |
| 1132 | if not args: |
| 1133 | raise TypeError( |
| 1134 | f"Parameter list to {cls.__qualname__}[...] cannot be empty" |
| 1135 | ) |
| 1136 | if not all(_is_typevar_like(p) for p in args): |
| 1137 | raise TypeError( |
| 1138 | f"Parameters to {cls.__name__}[...] must all be type variables " |
| 1139 | f"or parameter specification variables.") |
| 1140 | if len(set(args)) != len(args): |
| 1141 | raise TypeError( |
| 1142 | f"Parameters to {cls.__name__}[...] must all be unique") |
| 1143 | else: |
| 1144 | # Subscripting a regular Generic subclass. |
| 1145 | try: |
| 1146 | parameters = cls.__parameters__ |
| 1147 | except AttributeError as e: |
| 1148 | init_subclass = getattr(cls, '__init_subclass__', None) |
| 1149 | if init_subclass not in {None, Generic.__init_subclass__}: |
| 1150 | e.add_note( |
| 1151 | f"Note: this exception may have been caused by " |
| 1152 | f"{init_subclass.__qualname__!r} (or the " |
| 1153 | f"'__init_subclass__' method on a superclass) not " |
| 1154 | f"calling 'super().__init_subclass__()'" |
| 1155 | ) |
| 1156 | raise |
| 1157 | for param in parameters: |
| 1158 | prepare = getattr(param, '__typing_prepare_subst__', None) |
| 1159 | if prepare is not None: |
| 1160 | args = prepare(cls, args) |
| 1161 | _check_generic_specialization(cls, args) |
| 1162 | |
| 1163 | new_args = [] |
| 1164 | for param, new_arg in zip(parameters, args): |
| 1165 | if isinstance(param, TypeVarTuple): |
| 1166 | new_args.extend(new_arg) |
| 1167 | else: |
| 1168 | new_args.append(new_arg) |
| 1169 | args = tuple(new_args) |
| 1170 | |
| 1171 | return _GenericAlias(cls, args) |
nothing calls this directly
no test coverage detected