1- """The main ``basedtyping`` module. the types/functions defined here can be used at both type-time and at runtime."""
1+ """The main ``basedtyping`` module. the types/functions defined here can be used at
2+ both type-time and at runtime.
3+ """
24
35from __future__ import annotations
46
@@ -105,7 +107,8 @@ def __rand__(self, other: object) -> object:
105107 # for isinstance checks
106108 Function = Callable
107109
108- # Unlike the generics in other modules, these are meant to be imported to save you from the boilerplate
110+ # Unlike the generics in other modules, these are meant to be imported to save you
111+ # from the boilerplate
109112T = TypeVar ("T" )
110113in_T = TypeVar ("in_T" , contravariant = True )
111114out_T = TypeVar ("out_T" , covariant = True )
@@ -143,7 +146,8 @@ class NotReifiedError(ReifiedGenericError):
143146
144147
145148class NotEnoughTypeParametersError (ReifiedGenericError ):
146- """Raised when type parameters are passed to a ``ReifiedGeneric`` with an incorrect number of type parameters:
149+ """Raised when type parameters are passed to a ``ReifiedGeneric`` with an
150+ incorrect number of type parameters:
147151
148152 for example:
149153 >>> class Foo(ReifiedGeneric[Tuple[T, U]]):
@@ -155,20 +159,25 @@ class NotEnoughTypeParametersError(ReifiedGenericError):
155159
156160
157161class _ReifiedGenericMetaclass (type ):
158- # these should really only be on the class not the metaclass, but since it needs to be accessible from both instances and the class itself, its duplicated here
162+ # these should really only be on the class not the metaclass,
163+ # but since it needs to be accessible from both instances and the class itself,
164+ # its duplicated here
159165
160166 __reified_generics__ : tuple [type , ...]
161167 """should be a generic but cant due to https://github.com/python/mypy/issues/11672"""
162168
163169 __type_vars__ : tuple [TypeVar , ...]
164- """``TypeVar``s that have not yet been reified. so this Tuple should always be empty by the time the ``ReifiedGeneric`` is instanciated"""
170+ """``TypeVar``s that have not yet been reified. so this Tuple should always be empty
171+ by the time the ``ReifiedGeneric`` is instanciated"""
165172
166173 _orig_type_vars : tuple [TypeVar , ...]
167- """used internally to check the ``__type_vars__`` on the current ``ReifiedGeneric`` against the original one it was copied from
168- in ``ReifiedGeneric.__class_getitem__``"""
174+ """used internally to check the ``__type_vars__`` on the current ``ReifiedGeneric``
175+ against the original one it was copied from
176+ in ``ReifiedGeneric.__class_getitem__``"""
169177
170178 _can_do_instance_and_subclass_checks_without_generics : bool
171- """Used internally for ``isinstance`` and ``issubclass`` checks, ``True`` when the class can currenty be used in said checks without generics in them"""
179+ """Used internally for ``isinstance`` and ``issubclass`` checks, ``True``
180+ when the class can currenty be used in said checks without generics in them"""
172181
173182 def _orig_class (cls ) -> _ReifiedGenericMetaclass :
174183 """Gets the original class that ``ReifiedGeneric.__class_getitem__`` copied from"""
@@ -182,10 +191,12 @@ def _type_var_check(cls, args: tuple[type, ...]) -> bool:
182191 if cls ._has_non_reified_type_vars ():
183192 cls ._raise_generics_not_reified ()
184193 return True
185- assert len (cls ._orig_class ().__parameters__ ) == len (cls .__reified_generics__ ) == len (args ) # type: ignore[attr-defined]
194+ if len (cls ._orig_class ().__parameters__ ) != len (cls .__reified_generics__ ) == len (args ): # type: ignore[attr-defined]
195+ raise RuntimeError
186196 for parameter , self_arg , subclass_arg in zip (
187- # normal generics use __parameters__, we use __type_vars__ because the Generic base class deletes properties
188- # named __parameters__ when copying to a new class
197+ # normal generics use __parameters__, we use __type_vars__ because the
198+ # Generic base class deletes properties named __parameters__ when copying
199+ # to a new class
189200 cast (
190201 Tuple [TypeVar , ...],
191202 cls ._orig_class ().__parameters__ , # type: ignore[attr-defined]
@@ -239,9 +250,10 @@ def __subclasscheck__(cls, subclass: object) -> bool:
239250 return False
240251 if cls ._can_do_instance_and_subclass_checks_without_generics :
241252 return True
242- # if one of the classes doesn't have any generics, we treat it as the widest possible values for those generics (like star projection)
253+ # if one of the classes doesn't have any generics, we treat it as the widest
254+ # possible values for those generics (like star projection)
243255 if not hasattr (subclass , "__reified_generics__" ):
244- # TODO: subclass could be wider, but we don't know for sure because cls could have generics matching its bound
256+ # TODO: subclass could be wider, but we don't know for sure because cls could have generics matching its bound # noqa: TD003
245257 raise NotImplementedError (
246258 "Cannot perform a subclass check where the first class"
247259 f" ({ cls .__name__ !r} ) has type parameters and the second class"
@@ -258,9 +270,7 @@ def __instancecheck__(cls, instance: object) -> bool:
258270 return False
259271 if cls ._can_do_instance_and_subclass_checks_without_generics :
260272 return True
261- return cls ._type_var_check (
262- cast (ReifiedGeneric [object ], instance ).__reified_generics__
263- )
273+ return cls ._type_var_check (cast (ReifiedGeneric [object ], instance ).__reified_generics__ )
264274
265275 # need the generic here for pyright. see https://github.com/microsoft/pyright/issues/5488
266276 def __call__ (cls : type [T ], * args : object , ** kwargs : object ) -> T :
@@ -317,21 +327,24 @@ class ReifiedGeneric(Generic[T], metaclass=_ReifiedGenericMetaclass):
317327 >>> isinstance(Foo[int, str](), Foo[int, int]) # type: ignore[misc]
318328 False
319329
320- note: basedmypy currently doesn't allow generics in ``isinstance`` and ``issubclass`` checks, so for now you have to use
321- ``basedtyping.issubform`` for subclass checks and ``# type: ignore[misc]`` for instance checks. this issue
322- is tracked [here](https://github.com/KotlinIsland/basedmypy/issues/5)
330+ note: basedmypy currently doesn't allow generics in ``isinstance`` and
331+ ``issubclass`` checks, so for now you have to use ``basedtyping.issubform`` for
332+ subclass checks and ``# type: ignore[misc]`` for instance checks. this issue
333+ is tracked [here](https://github.com/KotlinIsland/basedmypy/issues/5)
323334 """
324335
325336 __reified_generics__ : tuple [type , ...]
326337 """Should be a generic but cant due to https://github.com/KotlinIsland/basedmypy/issues/142"""
327338 __type_vars__ : tuple [TypeVar , ...]
328- """``TypeVar``\\ s that have not yet been reified. so this Tuple should always be empty by the time the ``ReifiedGeneric`` is instantiated"""
339+ """``TypeVar``\\ s that have not yet been reified. so this Tuple should always be\
340+ empty by the time the ``ReifiedGeneric`` is instantiated"""
329341
330342 @_tp_cache # type: ignore[no-any-expr, misc]
331343 def __class_getitem__ ( # type: ignore[no-any-decorated]
332344 cls , item : GenericItems
333345 ) -> type [ReifiedGeneric [T ]]:
334- # when defining the generic (ie. `class Foo(ReifiedGeneric[T]):`) we want the normal behavior
346+ # when defining the generic (ie. `class Foo(ReifiedGeneric[T]):`) we
347+ # want the normal behavior
335348 if cls is ReifiedGeneric :
336349 # https://github.com/KotlinIsland/basedtypeshed/issues/7
337350 return super ().__class_getitem__ (item ) # type: ignore[misc, no-any-return]
@@ -344,17 +357,19 @@ def __class_getitem__( # type: ignore[no-any-decorated]
344357 for generic in (
345358 cls .__reified_generics__ if hasattr (cls , "__reified_generics__" ) else ()
346359 )
347- # TODO: investigate this unreachable, redundant-expr
360+ # TODO: investigate this unreachable, redundant-expr # noqa: TD003
348361 if not isinstance (generic , TypeVar ) # type: ignore[unused-ignore, unreachable, redundant-expr, no-any-expr]
349362 )
350363
351- # normal generics use __parameters__, we use __type_vars__ because the Generic base class deletes properties
352- # named __parameters__ when copying to a new class
364+ # normal generics use __parameters__, we use __type_vars__ because the
365+ # Generic base class deletes properties named __parameters__ when copying
366+ # to a new class
353367 orig_type_vars = (
354368 cls .__type_vars__
355369 if hasattr (cls , "__type_vars__" )
356370 else cast (
357- Tuple [TypeVar , ...], cls .__parameters__ # type:ignore[attr-defined]
371+ Tuple [TypeVar , ...],
372+ cls .__parameters__ , # type:ignore[attr-defined]
358373 )
359374 )
360375
@@ -367,23 +382,24 @@ def __class_getitem__( # type: ignore[no-any-decorated]
367382 "Incorrect number of type parameters specified. expected length:"
368383 f" { expected_length } , actual length { actual_length } "
369384 )
370- ReifiedGenericCopy : type [ReifiedGeneric [T ]] = type (
385+ reified_generic_copy : type [ReifiedGeneric [T ]] = type (
371386 cls .__name__ ,
372387 (
373388 cls , # make the copied class extend the original so normal instance checks work
374389 ),
375- # TODO: proper type
390+ # TODO: proper type # noqa: TD003
376391 { # type: ignore[no-any-expr]
377392 "__reified_generics__" : tuple ( # type: ignore[no-any-expr]
378- _type_convert (t ) for t in items # type: ignore[unused-ignore, no-any-expr]
393+ _type_convert (t )
394+ for t in items # type: ignore[unused-ignore, no-any-expr]
379395 ),
380396 "_orig_type_vars" : orig_type_vars ,
381397 "__type_vars__" : _collect_parameters (items ), # type: ignore[name-defined]
382398 },
383399 )
384400 # can't set it in the dict above otherwise __init_subclass__ overwrites it
385- ReifiedGenericCopy ._can_do_instance_and_subclass_checks_without_generics = False
386- return ReifiedGenericCopy
401+ reified_generic_copy ._can_do_instance_and_subclass_checks_without_generics = False
402+ return reified_generic_copy
387403
388404 def __init_subclass__ (cls ):
389405 cls ._can_do_instance_and_subclass_checks_without_generics = True
@@ -400,9 +416,9 @@ def __init_subclass__(cls):
400416 _Forms : TypeAlias = Union [type , _SpecialForm , typing_extensions ._SpecialForm ]
401417
402418
403- # TODO: make this work with any "form", not just unions
419+ # TODO: make this work with any "form", not just unions # noqa: TD003
404420# should be (form: TypeForm, forminfo: TypeForm)
405- # TODO: form/forminfo can include _UnionGenericAlias
421+ # TODO: form/forminfo can include _UnionGenericAlias # noqa: TD003
406422def issubform (form : _Forms , forminfo : _Forms ) -> bool :
407423 """EXPERIMENTAL: Warning, this function currently only supports unions and ``Never``.
408424
@@ -425,7 +441,8 @@ def issubform(form: _Forms, forminfo: _Forms) -> bool:
425441 # Morally, form is an instance of "UnionType | _UnionGenericAlias"
426442 # But _UnionGenericAlias doesn't have any representation at type time.
427443 return all (
428- issubform (t , forminfo ) for t in cast (Sequence [type ], form .__args__ ) # type: ignore[union-attr]
444+ issubform (t , forminfo )
445+ for t in cast (Sequence [type ], form .__args__ ) # type: ignore[union-attr]
429446 )
430447 if sys .version_info < (3 , 10 ) and isinstance (forminfo , OldUnionType ):
431448 # Morally, forminfo is an instance of "_UnionGenericAlias"
@@ -445,8 +462,9 @@ def issubform(form: _Forms, forminfo: _Forms) -> bool:
445462elif sys .version_info >= (3 , 9 ):
446463
447464 @_BasedSpecialForm
448- def Untyped (
449- self : _BasedSpecialForm , parameters : object # noqa: ARG001
465+ def Untyped ( # noqa: N802
466+ self : _BasedSpecialForm ,
467+ parameters : object , # noqa: ARG001
450468 ) -> NoReturn :
451469 """Special type indicating that something isn't typed.
452470
@@ -465,7 +483,7 @@ def Untyped(
465483
466484
467485class _IntersectionGenericAlias (_BasedGenericAlias , _root = True ):
468- def copy_with (self , args : object ) -> Self : # type: ignore[override] # TODO: put in the overloads
486+ def copy_with (self , args : object ) -> Self : # type: ignore[override] # TODO: put in the overloads # noqa: TD003
469487 return cast (Self , Intersection [args ])
470488
471489 def __eq__ (self , other : object ) -> bool :
@@ -490,7 +508,7 @@ def __reduce__(self) -> (object, object):
490508if sys .version_info > (3 , 9 ):
491509
492510 @_BasedSpecialForm
493- def Intersection (self : _BasedSpecialForm , parameters : object ) -> object :
511+ def Intersection (self : _BasedSpecialForm , parameters : object ) -> object : # noqa: N802
494512 """Intersection type; Intersection[X, Y] means both X and Y.
495513
496514 To define an intersection:
@@ -531,9 +549,7 @@ def Intersection(self: _BasedSpecialForm, parameters: object) -> object:
531549 return _IntersectionGenericAlias (self , parameters ) # type: ignore[arg-type, no-any-expr]
532550
533551else :
534- Intersection = _BasedSpecialForm (
535- "Intersection" , doc = "" , alias = _IntersectionGenericAlias
536- )
552+ Intersection = _BasedSpecialForm ("Intersection" , doc = "" , alias = _IntersectionGenericAlias )
537553
538554
539555class _TypeFormForm (_BasedSpecialForm , _root = True ): # type: ignore[misc]
@@ -548,11 +564,13 @@ def __getitem__(self, parameters: object | tuple[object]) -> _BasedGenericAlias:
548564 return _BasedGenericAlias (self , parameters ) # type: ignore[arg-type]
549565
550566
551- TypeForm = _TypeFormForm (doc = """\
552- A type that can be used to represent a ``builtins.type`` or a ``SpecialForm``.
553- For example:
554-
555- def f[T](t: TypeForm[T]) -> T: ...
556-
557- reveal_type(f(int | str)) # int | str
558- """ )
567+ TypeForm = _TypeFormForm (
568+ doc = """\
569+ A type that can be used to represent a ``builtins.type`` or a ``SpecialForm``.
570+ For example:
571+
572+ def f[T](t: TypeForm[T]) -> T: ...
573+
574+ reveal_type(f(int | str)) # int | str
575+ """
576+ )
0 commit comments