Repository navigation
Expand file tree
/
Copy path_defbase_ctypinit.py
More file actions
2007 lines (1753 loc) · 78.1 KB
/
Copy path_defbase_ctypinit.py
File metadata and controls
2007 lines (1753 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from ctypes import *
import sys
if sys.implementation.name != 'cpython':
raise RuntimeError('Only CPython interpreter implementation supported.')
defined_Py_TRACE_REFS = hasattr(sys, 'getobjects')
if sys.version_info[0:2] == (3, 14):
if not hasattr(sys, '_is_gil_enabled'):
GIL_ENABLED = True
else:
GIL_ENABLED = sys._is_gil_enabled()
from typing import (TypeVar, Generic, Optional,
Mapping, Any, Dict,
AnyStr, Sequence, Type,
Iterable, Callable, List)
import typing, ctypes, types, collections.abc
import traceback
if sys.version_info < (3, 8):
raise RuntimeError('Versions before 3.8 are not supported.')
if sys.version_info >= (3, 15):
raise RuntimeError('Versions after 3.14 are not supported.')
_INIT_CHAIN: List[Callable[[], None]] = []
_GLOBAL_REFS: List[Any] = []
mappingproxy = type(type.__dict__)
PY_SINGLE_FUNC = PYFUNCTYPE(c_void_p, c_void_p)
PY_SINGLE_WITH_ERR_FUNC = PYFUNCTYPE(c_int, c_void_p)
PY_BINARY_FUNC = PYFUNCTYPE(c_void_p, c_void_p, c_void_p)
PY_BINARY_WITH_ERR_FUNC = PYFUNCTYPE(c_int, c_void_p, c_void_p)
PY_TERNARY_FUNC = PYFUNCTYPE(c_void_p, c_void_p, c_void_p, c_void_p)
PY_TERNARY_WITH_ERR_FUNC = PYFUNCTYPE(c_int, c_void_p, c_void_p, c_void_p)
class POLYFILL_SpecialForm(typing._Final, _root=True):
__slots__ = ('_name', '__doc__', '_getitem')
def __init__(self, getitem):
self._getitem = getitem
self._name = getitem.__name__
self.__doc__ = getitem.__doc__
def __getattr__(self, item):
if item in {'__name__', '__qualname__'}:
return self._name
raise AttributeError(item)
def __mro_entries__(self, bases):
raise TypeError(f"Cannot subclass {self!r}")
def __repr__(self):
return f'typing.{self._name}'
def __reduce__(self):
return self._name
def __call__(self, *args, **kwds):
raise TypeError(f"Cannot instantiate {self!r}")
def __or__(self, other):
return typing.Union[self, other]
def __ror__(self, other):
return typing.Union[other, self]
def __instancecheck__(self, obj):
raise TypeError(f"{self} cannot be used with isinstance()")
def __subclasscheck__(self, cls):
raise TypeError(f"{self} cannot be used with issubclass()")
@typing._tp_cache
def __getitem__(self, parameters):
return self._getitem(self, parameters)
if sys.version_info < (3, 13) or typing.TYPE_CHECKING:
def polyfill_sync_38_39_310_311_312_313():
_pfill_initchain = []
def p_init_39spec():
MProxy_Access(type.__dict__)['__class_getitem__'] = classmethod(lambda cls, item: typing._GenericAlias(cls, item))
tp_str = PyType_CAST_DEREF(str)
tp_str.immutable = False
tp_str.is_heap_type = True
def _removeprefix(self: str, prefix: str):
if self.startswith(prefix):
return self[len(prefix):]
return self
def _removesuffix(self: str, suffix: str):
if self.endswith(suffix):
return self[:-len(suffix)]
return self
MProxy_Access(str.__dict__)['removeprefix'] = _removeprefix
MProxy_Access(str.__dict__)['removesuffix'] = _removesuffix
str.removeprefix = _removeprefix
str.removesuffix = _removesuffix
tp_str.immutable = True
tp_str.is_heap_type = False
def p_init_310spec():
@POLYFILL_SpecialForm
def TypeGuard(self, parameters):
item = typing._type_check(parameters, f'{self} accepts only a single type.')
return typing._GenericAlias(self, (item,))
typing.TypeGuard = TypeGuard
class _Immutable:
__slots__ = ()
def __copy__(self): return self
def __deepcopy__(self, memo): return self
class ParamSpecArgs(_Immutable):
def __init__(self, origin):
self.__origin__ = origin
def __repr__(self):
return f"{self.__origin__.__name__}.args"
def __eq__(self, other):
if not isinstance(other, ParamSpecArgs):
return NotImplemented
return self.__origin__ == other.__origin__
class ParamSpecKwargs(_Immutable):
def __init__(self, origin):
self.__origin__ = origin
def __repr__(self):
return f"{self.__origin__.__name__}.kwargs"
def __eq__(self, other):
if not isinstance(other, ParamSpecKwargs):
return NotImplemented
return self.__origin__ == other.__origin__
typing.ParamSpecArgs = ParamSpecArgs
typing.ParamSpecKwargs = ParamSpecKwargs
def _set_default(type_param, default):
type_param.has_default = lambda: default is not typing.NoDefault
type_param.__default__ = default
class _DefaultMixin:
__slots__ = (); __init__ = _set_default
def _caller(depth=1, default='__main__'):
try:
return sys._getframemodulename(depth + 1) or default
except AttributeError:
pass
try:
return sys._getframe(depth + 1).f_globals.get('__name__', default)
except (AttributeError, ValueError):
pass
return None
class _DummyKwargsPlaceholder_NoDefault: pass
class ParamSpec(list, _DefaultMixin):
__class__ = typing.TypeVar
@property
def args(self):
return ParamSpecArgs(self)
@property
def kwargs(self):
return ParamSpecKwargs(self)
def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
infer_variance=False, default=_DummyKwargsPlaceholder_NoDefault):
if default is _DummyKwargsPlaceholder_NoDefault:
default = typing.NoDefault
list.__init__(self, [self])
self.__name__ = name
self.__covariant__ = bool(covariant)
self.__contravariant__ = bool(contravariant)
self.__infer_variance__ = bool(infer_variance)
if bound:
self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
else: self.__bound__ = None
_DefaultMixin.__init__(self, default)
def_mod = _caller()
if def_mod != 'typing_extensions':
self.__module__ = def_mod
def __repr__(self):
if self.__infer_variance__:
prefix = ''
elif self.__covariant__:
prefix = '+'
elif self.__contravariant__:
prefix = '-'
else:
prefix = '~'
return prefix + self.__name__
def __hash__(self): return object.__hash__(self)
def __eq__(self, other): return self is other
def __reduce__(self): return self.__name__
def __call__(self, *args, **kwargs): pass
typing.ParamSpec = ParamSpec
def _type_convert(arg, module=None, *, allow_special_forms=False):
if arg is None: return type(None)
if isinstance(arg, str):
if sys.version_info <= (3, 9, 6):
return typing.ForwardRef(arg)
if sys.version_info <= (3, 9, 7):
return typing.ForwardRef(arg, module=module)
return typing.ForwardRef(arg, module=module, is_class=allow_special_forms)
return arg
def _unpack_args(*args):
newargs = []
for arg in args:
subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
if subargs is not None and (not (subargs and subargs[-1] is ...)):
newargs.extend(subargs)
else:
newargs.append(arg)
return newargs
def _is_unpack(obj):
return typing.get_origin(obj) is typing.Unpack
def _is_param_expr(arg):
return arg is ... or isinstance(
arg,
(
tuple,
list,
ParamSpec,
typing._ConcatenateGenericAlias,
),
)
class _ConcatenateGenericAlias(list):
__class__ = typing._GenericAlias
def __init_subclass__(cls, *args, **kwargs):
super().__init_subclass__(*args)
def __init__(self, origin, args):
super().__init__(args)
self.__origin__ = origin
self.__args__ = args
def __repr__(self):
_type_repr = typing._type_repr
return (f'{_type_repr(self.__origin__)}'
f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
def __hash__(self):
return hash((self.__origin__, self.__args__))
def __call__(self, *args, **kwargs): pass
@property
def __parameters__(self):
return tuple(
tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
)
def copy_with(self, params):
if isinstance(params[-1], _ConcatenateGenericAlias):
params = (*params[:-1], *params[-1].__args__)
elif isinstance(params[-1], (list, tuple)):
return (*params[:-1], *params[-1])
elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))):
raise TypeError("The last parameter to Concatenate should be a "
"ParamSpec variable or ellipsis.")
return self.__class__(self.__origin__, params)
def __getitem__(self, args):
if self.__origin__ in (Generic, typing.Protocol):
raise TypeError(f"Cannot subscript already-subscripted {self}")
if not self.__parameters__:
raise TypeError(f"{self} is not a generic class")
if not isinstance(args, tuple):
args = (args,)
args = _unpack_args(*(_type_convert(p) for p in args))
params = self.__parameters__
for param in params:
prepare = getattr(param, "__typing_prepare_subst__", None)
if prepare is not None:
args = prepare(self, args)
elif isinstance(param, ParamSpec):
i = params.index(param)
if (
i == len(args)
and getattr(param, '__default__', typing.NoDefault) is not typing.NoDefault
):
args = [*args, param.__default__]
if i >= len(args):
raise TypeError(f"Too few arguments for {self}")
if len(params) == 1 and not _is_param_expr(args[0]):
assert i == 0
args = (args,)
elif (
isinstance(args[i], list)
and not isinstance(args[i], _ConcatenateGenericAlias)
):
args = (*args[:i], tuple(args[i]), *args[i + 1:])
alen = len(args)
plen = len(params)
if alen != plen:
raise TypeError(
f"Too {'many' if alen > plen else 'few'} arguments for {self};"
f" actual {alen}, expected {plen}"
)
subst = dict(zip(self.__parameters__, args))
new_args = []
for arg in self.__args__:
if isinstance(arg, type):
new_args.append(arg)
continue
if isinstance(arg, TypeVar):
arg = subst[arg]
if (
(isinstance(arg, typing._GenericAlias) and _is_unpack(arg))
or (
hasattr(types, "GenericAlias")
and isinstance(arg, types.GenericAlias)
and getattr(arg, "__unpacked__", False)
)
):
raise TypeError(f"{arg} is not valid as type argument")
elif isinstance(arg,
typing._GenericAlias
if not hasattr(types, "GenericAlias") else
(typing._GenericAlias, types.GenericAlias)
):
subparams = arg.__parameters__
if subparams:
subargs = tuple(subst[x] for x in subparams)
arg = arg[subargs]
new_args.append(arg)
return self.copy_with(tuple(new_args))
typing._ConcatenateGenericAlias = _ConcatenateGenericAlias
@typing._tp_cache
def _concatenate_getitem(self, parameters):
if parameters == (): raise TypeError("Cannot take a Concatenate of no types.")
if not isinstance(parameters, tuple): parameters = (parameters,)
if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)):
raise TypeError("The last parameter to Concatenate should be a "
"ParamSpec variable or ellipsis.")
msg = "Concatenate[arg, ...]: each arg must be a type."
parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]), parameters[-1])
return _create_concatenate_alias(self, parameters)
class _EllipsisDummy: ...
def _create_concatenate_alias(origin, parameters):
if parameters[-1] is ... and sys.version_info < (3, 9, 2):
parameters = (*parameters[:-1], _EllipsisDummy)
if sys.version_info >= (3, 10, 3):
concatenate = typing._ConcatenateGenericAlias(origin, parameters, _typevar_types=(TypeVar, ParamSpec),
_paramspec_tvars=True)
else:
concatenate = typing._ConcatenateGenericAlias(origin, parameters)
if parameters[-1] is not _EllipsisDummy: return concatenate
concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ... for p in concatenate.__args__)
if sys.version_info < (3, 10): return concatenate
concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__
if p is not _EllipsisDummy)
return concatenate
def get_origin(tp):
if isinstance(tp, typing._AnnotatedAlias): return typing.Annotated
if isinstance(tp, (typing._BaseGenericAlias, types.GenericAlias,
ParamSpecArgs, ParamSpecKwargs)):
return tp.__origin__
if tp is typing.Generic: return typing.Generic
return None
typing.get_origin = get_origin
def get_args(tp):
if isinstance(tp, typing._AnnotatedAlias): return (tp.__origin__, *tp.__metadata__)
if isinstance(tp, (typing._GenericAlias, types.GenericAlias)):
res = tp.__args__
if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
res = (list(res[:-1]), res[-1])
return res
return ()
typing.get_args = get_args
@POLYFILL_SpecialForm
def Concatenate(self, parameters):
return _concatenate_getitem(self, parameters)
typing.Concatenate = Concatenate
@POLYFILL_SpecialForm
def TypeAlias(self, parameters):
raise TypeError(f"{self} is not subscriptable")
typing.TypeAlias = TypeAlias
def _bit_count(self: int):
return bin(self).count("1")
tp_int = PyType_CAST_DEREF(int)
tp_int.immutable = False
tp_int.is_heap_type = True
MProxy_Access(int.__dict__)['bit_count'] = _bit_count
int.bit_count = _bit_count
tp_int.immutable = True
tp_int.is_heap_type = False
def p_init_311spec():
def _unpack_args(*args):
newargs = []
for arg in args:
subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
if subargs is not None and (not (subargs and subargs[-1] is ...)):
newargs.extend(subargs)
else:
newargs.append(arg)
return newargs
def _is_unpack(obj):
return typing.get_origin(obj) is typing.Unpack
class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True):
__module__ = "typing"
def copy_with(self, params):
if isinstance(params[-1], (list, tuple)):
return (*params[:-1], *params[-1])
if isinstance(params[-1], typing._ConcatenateGenericAlias):
params = (*params[:-1], *params[-1].__args__)
elif not (params[-1] is ... or isinstance(params[-1], typing.ParamSpec)):
raise TypeError("The last parameter to Concatenate should be a "
"ParamSpec variable or ellipsis.")
return super(typing._ConcatenateGenericAlias, self).copy_with(params)
def __getitem__(self, args):
value = super().__getitem__(args)
if isinstance(value, tuple) and any(_is_unpack(t) for t in value):
return tuple(_unpack_args(*(n for n in value)))
return value
typing._ConcatenateGenericAlias = _ConcatenateGenericAlias
@POLYFILL_SpecialForm
def Self(self, parameters):
raise TypeError(f"{self} is not subscriptable")
typing.Self = Self
@POLYFILL_SpecialForm
def Never(self, params):
raise TypeError(f"{self} is not subscriptable")
typing.Never = Never
@POLYFILL_SpecialForm
def Required(self, parameters):
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
typing.Required = Required
@POLYFILL_SpecialForm
def NotRequired(self, parameters):
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
typing.NotRequired = NotRequired
def assert_never(arg: Never) -> Never:
value = repr(arg)
if len(value) > 100:
value = value[:100] + '...'
raise AssertionError(f"Expected code to be unreachable, but got: {value}")
typing.assert_never = assert_never
def dataclass_transform(
*,
eq_default: bool = True,
order_default: bool = False,
kw_only_default: bool = False,
frozen_default: bool = False,
field_specifiers: typing.Tuple[
typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
...
] = (),
**kwargs: typing.Any,
) -> typing.Callable:
def decorator(cls_or_fn):
cls_or_fn.__dataclass_transform__ = {
"eq_default": eq_default,
"order_default": order_default,
"kw_only_default": kw_only_default,
"frozen_default": frozen_default,
"field_specifiers": field_specifiers,
"kwargs": kwargs,
}
return cls_or_fn
return decorator
typing.dataclass_transform = dataclass_transform
def reveal_type(obj):
print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
return obj
typing.reveal_type = reveal_type
def p_init_312spec():
class _UnpackSpecialForm(POLYFILL_SpecialForm, _root=True):
def __init__(self, getitem):
super().__init__(getitem)
class _UnpackAlias(typing._GenericAlias, _root=True):
if sys.version_info < (3, 11):
__class__ = typing.TypeVar
@property
def __typing_unpacked_tuple_args__(self):
assert self.__origin__ is Unpack
assert len(self.__args__) == 1
arg, = self.__args__
if isinstance(arg, typing._GenericAlias):
if arg.__origin__ is not tuple:
raise TypeError("Unpack[...] must be used with a tuple type")
return arg.__args__
return None
@property
def __typing_is_unpacked_typevartuple__(self):
assert self.__origin__ is Unpack
assert len(self.__args__) == 1
return isinstance(self.__args__[0], typing.TypeVarTuple)
def __getitem__(self, args):
if self.__typing_is_unpacked_typevartuple__:
return args
return super().__getitem__(args)
@_UnpackSpecialForm
def Unpack(self, parameters):
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
return _UnpackAlias(self, (item,))
_F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
def override(arg: _F) -> _F:
try:
arg.__override__ = True
except (AttributeError, TypeError):
pass
return arg
typing.override = override
ctypes.c_time_t = c_int32 if sizeof(c_void_p) == 4 else c_int64
def p_init_313spec():
class SingletonMeta(type):
def __setattr__(cls, attr, value):
raise TypeError(f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}")
class NoDefaultType(metaclass=SingletonMeta):
__slots__ = ()
def __new__(cls):
return globals().get("NoDefault") or object.__new__(cls)
def __repr__(self): return "typing.NoDefault"
def __reduce__(self): return "NoDefault"
NoDefault = NoDefaultType()
typing.NoDefault = NoDefault
@POLYFILL_SpecialForm
def ReadOnly(self, parameters):
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
def is_protocol(tp: type, /) -> bool:
return (
isinstance(tp, type)
and getattr(tp, '_is_protocol', False)
and tp is not typing.Protocol
)
typing.is_protocol = is_protocol
_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | {
"__match_args__", "__protocol_attrs__", "__non_callable_proto_members__",
"__final__",
}
def _get_protocol_attrs(cls):
attrs = set()
for base in cls.__mro__[:-1]:
if base.__name__ in {'Protocol', 'Generic'}:
continue
annotations = getattr(base, '__annotations__', {})
for attr in (*base.__dict__, *annotations):
if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
attrs.add(attr)
return attrs
def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
if not is_protocol(tp):
raise TypeError(f'{tp!r} is not a Protocol')
if hasattr(tp, '__protocol_attrs__'):
return frozenset(tp.__protocol_attrs__)
return frozenset(_get_protocol_attrs(tp))
typing.get_protocol_members = get_protocol_members
@POLYFILL_SpecialForm
def TypeIs(self, parameters):
item = typing._type_check(parameters, f'{self} accepts only a single type.')
return typing._GenericAlias(self, (item,))
typing.TypeIs = TypeIs
if sys.version_info >= (3, 8) or typing.TYPE_CHECKING:
if sys.version_info >= (3, 9) or typing.TYPE_CHECKING:
if sys.version_info >= (3, 10):
if sys.version_info >= (3, 11):
if sys.version_info >= (3, 12):
if sys.version_info >= (3, 13):
pass
else:
_pfill_initchain.append(p_init_313spec)
else:
_pfill_initchain.append(p_init_312spec)
_pfill_initchain.append(p_init_313spec)
else:
_pfill_initchain.append(p_init_311spec)
_pfill_initchain.append(p_init_312spec)
_pfill_initchain.append(p_init_313spec)
else:
_pfill_initchain.append(p_init_310spec)
_pfill_initchain.append(p_init_311spec)
_pfill_initchain.append(p_init_312spec)
_pfill_initchain.append(p_init_313spec)
else:
_pfill_initchain.append(p_init_39spec)
_pfill_initchain.append(p_init_310spec)
_pfill_initchain.append(p_init_311spec)
_pfill_initchain.append(p_init_312spec)
_pfill_initchain.append(p_init_313spec)
for init_cb in _pfill_initchain:
init_cb()
_INIT_CHAIN.append(polyfill_sync_38_39_310_311_312_313)
if sys.version_info[0:2] == (3, 8) or sys.version_info[0:2] == (3, 9) or typing.TYPE_CHECKING:
def polyfill_310plus_to_38_39():
tp_type = PyType_CAST_DEREF(type)
def polyfill_type_or(a, b):
self = cast(a, py_object).value
item = cast(b, py_object).value
union = typing.Union[self, item]
Py_INCREF(union)
return id(union)
pfn_polyfill_type_or = PY_BINARY_FUNC(polyfill_type_or)
_GLOBAL_REFS.append(pfn_polyfill_type_or)
if not tp_type.tp_as_number:
tp_type.tp_as_number = cast(PyObject_Malloc(36*sizeof(c_void_p)), POINTER(c_void_p))
memset(tp_type.tp_as_number, 0, 36*sizeof(c_void_p))
tp_type.tp_as_number[15] = cast(pfn_polyfill_type_or, c_void_p).value
tp_none = PyType_CAST_DEREF(type(None))
if not tp_none.tp_as_number:
tp_none.tp_as_number = cast(PyObject_Malloc(36*sizeof(c_void_p)), POINTER(c_void_p))
memset(tp_none.tp_as_number, 0, 36*sizeof(c_void_p))
tp_none.tp_as_number[15] = cast(pfn_polyfill_type_or, c_void_p).value
tp_specialform = PyType_CAST_DEREF(typing._SpecialForm)
if not tp_specialform.tp_as_number:
tp_specialform.tp_as_number = cast(PyObject_Malloc(36*sizeof(c_void_p)), POINTER(c_void_p))
memset(tp_specialform.tp_as_number, 0, 36*sizeof(c_void_p))
tp_specialform.tp_as_number[15] = cast(pfn_polyfill_type_or, c_void_p).value
tp_genericalias = PyType_CAST_DEREF(typing._GenericAlias)
if not tp_genericalias.tp_as_number:
tp_genericalias.tp_as_number = cast(PyObject_Malloc(36*sizeof(c_void_p)), POINTER(c_void_p))
memset(tp_genericalias.tp_as_number, 0, 36*sizeof(c_void_p))
tp_genericalias.tp_as_number[15] = cast(pfn_polyfill_type_or, c_void_p).value
tp_pycstructtype = PyType_CAST_DEREF(type(Structure))
if not tp_pycstructtype.tp_as_number:
tp_pycstructtype.tp_as_number = cast(PyObject_Malloc(36*sizeof(c_void_p)), POINTER(c_void_p))
memset(tp_pycstructtype.tp_as_number, 0, 36*sizeof(c_void_p))
tp_pycstructtype.tp_as_number[15] = cast(pfn_polyfill_type_or, c_void_p).value
tp_type.Reload()
type_check = typing._type_check
def polyfill_typing_type_check(arg, msg, is_argument=True):
try:
result = type_check(arg, msg, is_argument)
except TypeError:
if not callable(arg):
return arg
raise
return result
typing._type_check = polyfill_typing_type_check
_INIT_CHAIN.append(polyfill_310plus_to_38_39)
_CWT = TypeVar('_WT')
class IArray(Generic[_CWT]):
def __getitem__(self, index: int) -> _CWT: ...
def __setitem__(self, index: int, value: _CWT) -> _CWT: ...
class IPointer(IArray[_CWT]):
contents: _CWT
if sys.version_info >= (3, 8) and sys.version_info < (3, 12) or typing.TYPE_CHECKING:
class PyObject(Structure, Generic[_CWT]):
fields_extra = []
if defined_Py_TRACE_REFS:
fields_extra = [
('unusedPtr', c_void_p),
('unusedPtr2', c_void_p)
]
_fields_ = fields_extra + [
('unusedSizeT', c_ssize_t),
('_ob_type', c_void_p)
]
@property
def ob_type(self) -> IPointer['PyTypeObject']:
return cast(self._ob_type, PyTypeObject_PTR)
@ob_type.setter
def ob_type(self, ob_type: type):
self._ob_type = id(ob_type)
def __repr__(self) -> str:
return repr(cast(byref(self), py_object).value)
@property
def object(self) -> _CWT:
return cast(byref(self), py_object).value
@classmethod
def offset(cls, field: str) -> int:
return getattr(cls, field).offset
@property
def refcnt(self) -> int:
return self.unusedSizeT
@refcnt.setter
def refcnt(self, refcnt: int):
self.unusedSizeT = refcnt
class PyVarObject(PyObject[_CWT]):
_fields_ = [
('unusedSizeT', c_ssize_t)
]
elif sys.version_info >= (3, 12) and sys.version_info < (3, 15) or typing.TYPE_CHECKING:
if sys.version_info[0:2] != (3, 14):
class PyObject(Structure, Generic[_CWT]):
fields_extra = []
if defined_Py_TRACE_REFS:
fields_extra = [
('unusedPtr', c_void_p),
('unusedPtr2', c_void_p)
]
_fields_ = fields_extra + [
('unusedInt64', c_ssize_t),
('_ob_type', c_void_p)
]
@property
def ob_type(self) -> IPointer['PyTypeObject']:
return cast(self._ob_type, PyTypeObject_PTR)
@ob_type.setter
def ob_type(self, ob_type: type):
self._ob_type = id(ob_type)
def __repr__(self) -> str:
return repr(self.object)
@property
def object(self) -> _CWT:
return cast(byref(self), py_object).value
@classmethod
def offset(cls, field: str) -> int:
return getattr(cls, field).offset
@property
def refcnt(self) -> int:
return self.unusedInt64
@refcnt.setter
def refcnt(self, refcnt: int):
self.unusedInt64 = refcnt
else:
if GIL_ENABLED:
class PyObject(Structure, Generic[_CWT]):
class _Refcnt(Union):
_fields_ = [
('ob_flags', c_uint16),
('ob_overflow', c_uint16),
('ob_refcnt', c_uint32)
]
_fields_ = [
('ob_refcnt', _Refcnt),
('_ob_type', c_void_p)
]
@property
def ob_type(self) -> IPointer['PyTypeObject']:
return cast(self._ob_type, PyTypeObject_PTR)
@ob_type.setter
def ob_type(self, ob_type: type):
self._ob_type = id(ob_type)
def __repr__(self) -> str:
return repr(self.object)
@property
def object(self) -> _CWT:
return cast(byref(self), py_object).value
@classmethod
def offset(cls, field: str) -> int:
return getattr(cls, field).offset
@property
def refcnt(self) -> int:
return self.unusedInt64
@refcnt.setter
def refcnt(self, refcnt: int):
self.unusedInt64 = refcnt
else:
class PyObject(Structure, Generic[_CWT]):
_fields_ = [
('ob_tid', c_int64),
('ob_flags', c_uint16),
('ob_mutex', c_uint8),
('ob_gc_bits', c_uint8),
('ob_ref_local', c_uint32),
('ob_ref_shared', c_ssize_t),
('_ob_type', c_void_p)
]
@property
def ob_type(self) -> IPointer['PyTypeObject']:
return cast(self._ob_type, PyTypeObject_PTR)
@ob_type.setter
def ob_type(self, ob_type: type):
self._ob_type = id(ob_type)
def __repr__(self) -> str:
return repr(self.object)
@property
def object(self) -> _CWT:
return cast(byref(self), py_object).value
@classmethod
def offset(cls, field: str) -> int:
return getattr(cls, field).offset
@property
def refcnt(self) -> int:
return self.ob_ref_local
@refcnt.setter
def refcnt(self, refcnt: int):
self.ob_ref_local = refcnt
class PyVarObject(PyObject[_CWT]):
_fields_ = [
('unusedSizeT', c_ssize_t)
]
PyObject_PTR = POINTER(PyObject)
def _wrap_flag(typ: type, name: str, flag: int, method_suffix: str = 'Flag'):
has_flag = f'Has{method_suffix}'
set_flag = f'Set{method_suffix}'
remove_flag = f'Remove{method_suffix}'
def getter(self) -> bool:
return getattr(self, has_flag)(flag)
getter.__name__ = name
getter_prop = property(getter)
def setter(self, value: bool):
if value:
getattr(self, set_flag)(flag)
else:
getattr(self, remove_flag)(flag)
setter.__name__ = name
setter_prop = getter_prop.setter(setter)
setattr(typ, name, getter_prop)
setattr(typ, name, setter_prop)
class PyMemberDef(Structure):
_fields_ = [
('name', c_char_p),
('type', c_int),
('offset', c_ssize_t),
('flags', c_int),
('unusedPtr', c_void_p)
]
name: bytes
flags: int
def SetFlag(self, flag: int):
if self.flags & flag: return
self.flags |= flag
def RemoveFlag(self, flag: int):
if not self.flags & flag: return
self.flags &= (~flag)
def HasFlag(self, flag: int) -> bool:
return (self.flags & flag) != 0
def EnumFlags(self) -> Sequence[str]:
result: List[str] = []
if self.HasFlag(Py_READONLY):
result.append('Py_READONLY')
if self.HasFlag(Py_AUDIT_READ):
result.append('Py_AUDIT_READ')
if self.HasFlag(_Py_WRITE_RESTRICTED):
result.append('_Py_WRITE_RESTRICTED')
if self.HasFlag(Py_RELATIVE_OFFSET):
result.append('Py_RELATIVE_OFFSET')
return tuple(result)
def __repr__(self) -> str:
repr_string: str = f"<member '{self.name.decode()}'"
if self.HasFlag(Py_READONLY):
repr_string += ', read-only'
repr_string += '>'
return repr_string
is_relative_offset: bool
_write_restricted: bool
audit_read: bool
readonly: bool
def __init__(self, name: AnyStr=None,
type: int=0, offset: int=0,
flags: int=0, doc: AnyStr=None):
if isinstance(name, str): name = name.encode()
if isinstance(doc, str): doc = doc.encode()
super().__init__(name, type, offset, flags, doc)
@classmethod
def array(self, members: Iterable['PyMemberDef']) -> IArray['PyMemberDef']:
if not isinstance(members, list): members = list(members)
members.append(PyMemberDef())
members_array = (PyMemberDef * len(members))(*members)
PyObject_CAST_DEREF(members_array).refcnt = 0xffffffff
return members_array
PyMemberDef_PTR = POINTER(PyMemberDef)
PY_GETTER = PYFUNCTYPE(c_void_p, c_void_p, c_void_p)
PY_SETTER = PYFUNCTYPE(c_int, c_void_p, c_void_p, c_void_p)
class PyGetSetDef(Structure):
_fields_ = [
('name', c_char_p),
('getter', c_void_p),
('setter', c_void_p),
('doc', c_char_p),
('closure', c_void_p)
]
name: bytes
getter: int
setter: int
doc: bytes
closure: int
PyGetSetDef_PTR = POINTER(PyGetSetDef)
# Types
Py_T_SHORT = 0
Py_T_INT = 1
Py_T_LONG = 2
Py_T_FLOAT = 3
Py_T_DOUBLE = 4
Py_T_STRING = 5
_Py_T_OBJECT = 6 # Deprecated, use Py_T_OBJECT_EX instead
# the ordering here is weird for binary compatibility
Py_T_CHAR = 7 # 1-character string
Py_T_BYTE = 8 # 8-bit signed int
# unsigned variants:
Py_T_UBYTE = 9
Py_T_USHORT = 10
Py_T_UINT = 11
Py_T_ULONG = 12
# Added by Jack: strings contained in the structure
Py_T_STRING_INPLACE = 13
# Added by Lillo: bools contained in the structure (assumed char)
Py_T_BOOL = 14
Py_T_OBJECT_EX = 16
Py_T_LONGLONG = 17
Py_T_ULONGLONG = 18
Py_T_PYSSIZET = 19 # Py_ssize_t
_Py_T_NONE = 20 # Deprecated. Value is always None.
Py_READONLY = 1
Py_AUDIT_READ = 2 # Added in 3.10, harmless no-op before that
_Py_WRITE_RESTRICTED = 4 # Deprecated, no-op. Do not reuse the value.
Py_RELATIVE_OFFSET = 8
_wrap_flag(PyMemberDef, 'readonly', Py_READONLY)
_wrap_flag(PyMemberDef, 'audit_read', Py_AUDIT_READ)
_wrap_flag(PyMemberDef, '_write_restricted', _Py_WRITE_RESTRICTED)
_wrap_flag(PyMemberDef, 'is_relative_offset', Py_RELATIVE_OFFSET)
class MProxy(PyObject[_CWT]):
_fields_ = [
('mapping', PyObject_PTR)
]
mapping: IPointer[PyObject[_CWT]]
PyMappingProxyObject_PTR = POINTER(MProxy)
def PyMappingProxyObject_CAST(obj: _CWT) -> MProxy[_CWT]:
return cast(id(obj), PyMappingProxyObject_PTR)
_Py_TPFLAGS_STATIC_BUILTIN = (1 << 1)
Py_TPFLAGS_MANAGED_WEAKREF = (1 << 3)
"""
Placement of dict (and values) pointers are managed by the VM, not by the type.
The VM will automatically set tp_dictoffset.
"""
Py_TPFLAGS_MANAGED_DICT = (1 << 4)
Py_TPFLAGS_PREHEADER = (Py_TPFLAGS_MANAGED_WEAKREF | Py_TPFLAGS_MANAGED_DICT)
# Set if instances of the type object are treated as sequences for pattern matching
Py_TPFLAGS_SEQUENCE = (1 << 5)
# Set if instances of the type object are treated as mappings for pattern matching
Py_TPFLAGS_MAPPING = (1 << 6)
"""
Disallow creating instances of the type: set tp_new to NULL and don't create
the "__new__" key in the type dictionary.
"""
Py_TPFLAGS_DISALLOW_INSTANTIATION = (1 << 7)
Py_TPFLAGS_IMMUTABLETYPE = (1 << 8)
Py_TPFLAGS_HEAPTYPE = (1 << 9)
Py_TPFLAGS_BASETYPE = (1 << 10)
Py_TPFLAGS_HAVE_VECTORCALL = (1 << 11)
Py_TPFLAGS_READY = (1 << 12)
Py_TPFLAGS_READYING = (1 << 13)
Py_TPFLAGS_HAVE_GC = (1 << 14)
# These two bits are preserved for Stackless Python, next after this is 17
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION = (3 << 15)
# Objects behave like an unbound method
Py_TPFLAGS_METHOD_DESCRIPTOR = (1 << 17)
# Object has up-to-date type attribute cache
Py_TPFLAGS_VALID_VERSION_TAG = (1 << 19)
# Type is abstract and cannot be instantiated
Py_TPFLAGS_IS_ABSTRACT = (1 << 20)
# This undocumented flag gives certain built-ins their unique pattern-matching
# behavior, which allows a single positional subpattern to match against the
# subject itself (rather than a mapped attribute on it):
_Py_TPFLAGS_MATCH_SELF = (1 << 22)
# Items (ob_size*tp_itemsize) are found at the end of an instance's memory
Py_TPFLAGS_ITEMS_AT_END = (1 << 23)
# These flags are used to determine if a type is a subclass.
Py_TPFLAGS_LONG_SUBCLASS = (1 << 24)
Py_TPFLAGS_LIST_SUBCLASS = (1 << 25)
Py_TPFLAGS_TUPLE_SUBCLASS = (1 << 26)
Py_TPFLAGS_BYTES_SUBCLASS = (1 << 27)