Repository navigation
Expand file tree
/
Copy path_typesmodule.c
More file actions
1431 lines (1245 loc) · 40.5 KB
/
Copy path_typesmodule.c
File metadata and controls
1431 lines (1245 loc) · 40.5 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
// C accelerator for the types modules
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#include "pycore_critical_section.h" // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED
#include "pycore_descrobject.h" // _PyMethodWrapper_Type
#include "pycore_function.h" // _PyFunction_SetCode
#include "pycore_genobject.h" // _PyGen_GetCode
#include "pycore_namespace.h" // _PyNamespace_Type
#include "pycore_object.h" // _PyNone_Type, _PyNotImplemented_Type
#include "pycore_unionobject.h" // _PyUnion_Type
/*[clinic input]
module _types
class _types.DynamicClassAttribute "DynamicClassAttribute *" ""
class _types._GeneratorWrapper "GeneratorWrapper *" ""
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a06e33066648ee59]*/
typedef struct {
PyObject *DynamicClassAttribute;
PyObject *_GeneratorWrapper;
PyObject *_collections_abc_Coroutine;
PyObject *_collections_abc_Generator;
} types_state;
static types_state *
get_module_state(PyObject *module)
{
assert(PyModule_Check(module));
types_state *state = PyModule_GetState(module);
assert(state != NULL);
return state;
}
typedef struct _DynamicClassAttribute DynamicClassAttribute;
typedef struct _GeneratorWrapper GeneratorWrapper;
#include "clinic/_typesmodule.c.h"
PyDoc_STRVAR(types__doc__,
"A helper for the types module.");
static PyObject *
generator_as_coroutine(PyObject *func, PyCodeObject *code)
{
/* Equivalent to calling code.replace(co_flags=code.co_flags | CO_ITERABLE_COROUTINE) */
PyObject *method = PyObject_GetAttrString((PyObject *)code, "replace");
if (method == NULL)
{
return NULL;
}
// We could optimize this by manually constructing a code object
// with all the fields instead of calling replace().
// However, this is much simpler if we don't.
int new_flags = code->co_flags;
new_flags |= CO_ITERABLE_COROUTINE;
PyObject *kwargs = Py_BuildValue("{s:i}", "co_flags", new_flags);
if (kwargs == NULL)
{
Py_DECREF(method);
return NULL;
}
PyObject *new_code = PyObject_VectorcallDict(method, NULL, 0, kwargs);
Py_DECREF(method);
Py_DECREF(kwargs);
if (new_code == NULL)
{
return NULL;
}
if (_PyFunction_SetCode(func, new_code) < 0) {
Py_DECREF(new_code);
return NULL;
}
Py_DECREF(new_code);
return Py_NewRef(func);
}
static int
init_state_collections(types_state *state)
{
assert(state->_collections_abc_Generator == NULL);
assert(state->_collections_abc_Coroutine == NULL);
PyObject *_collections_abc = PyImport_ImportModule("_collections_abc");
if (_collections_abc == NULL) {
return -1;
}
PyObject *generator = PyObject_GetAttrString(_collections_abc, "Generator");
if (generator == NULL) {
Py_DECREF(_collections_abc);
return -1;
}
state->_collections_abc_Generator = generator;
PyObject *coroutine = PyObject_GetAttrString(_collections_abc, "Coroutine");
if (coroutine == NULL) {
Py_DECREF(_collections_abc);
return -1;
}
state->_collections_abc_Coroutine = coroutine;
Py_DECREF(_collections_abc);
return 0;
}
static PyObject *
generatorwrapper_fast_new(PyObject *self, PyObject *wrapped);
static PyObject *
wrapped_decorator(PyObject *transport, PyObject *args, PyObject *kwargs)
{
assert(PyTuple_CheckExact(transport));
PyObject *mod = PyTuple_GET_ITEM(transport, 0);
PyObject *func = PyTuple_GET_ITEM(transport, 1);
PyObject *coro = PyObject_Call(func, args, kwargs);
if (coro == NULL)
{
return NULL;
}
if (PyCoro_CheckExact(coro))
{
return coro;
}
if (PyGen_CheckExact(coro))
{
PyCodeObject *code = _PyGen_GetCode((PyGenObject *)coro);
if (code->co_flags & CO_ITERABLE_COROUTINE)
{
return coro;
}
}
types_state *state = get_module_state(mod);
if (state->_collections_abc_Generator == NULL)
{
if (init_state_collections(state) < 0)
{
Py_DECREF(coro);
return NULL;
}
}
assert(state->_collections_abc_Generator != NULL);
assert(state->_collections_abc_Coroutine != NULL);
int is_coroutine = PyObject_IsInstance(coro,
state->_collections_abc_Coroutine);
if (is_coroutine < 0) {
Py_DECREF(coro);
return NULL;
}
if (is_coroutine) {
return coro;
}
int is_generator = PyObject_IsInstance(coro,
state->_collections_abc_Generator);
if (is_generator < 0) {
Py_DECREF(coro);
return NULL;
}
if (is_generator) {
// Something that implements the generator protocol, but
// not the coroutine protocol. Wrap it.
PyObject *wrapped = generatorwrapper_fast_new(mod, coro);
Py_DECREF(coro);
return wrapped;
}
// No idea what it is, let it through
return coro;
}
const PyMethodDef wrapped_decorator_md = {
.ml_name = "wrapped_decorator",
.ml_meth = (PyCFunction)wrapped_decorator,
.ml_flags = METH_VARARGS|METH_KEYWORDS
};
struct _GeneratorWrapper {
PyObject_HEAD;
PyObject *wrapped;
int isgen;
};
static int copy_attribute(PyObject *dst, PyObject *src, PyObject *name)
{
assert(dst != NULL);
assert(src != NULL);
assert(name != NULL);
PyObject *attr;
if (PyObject_GetOptionalAttr(src, name, &attr) < 0) {
return -1;
}
if (attr == NULL) {
attr = Py_None;
}
assert(attr != NULL);
if (PyObject_SetAttr(dst, name, attr) < 0) {
Py_DECREF(attr);
return -1;
}
Py_DECREF(attr);
return 0;
}
static int generatorwrapper_fast_init(PyObject *self, PyObject *wrapped)
{
assert(self != NULL);
assert(wrapped != NULL);
if (copy_attribute(self, wrapped, &_Py_ID(__name__)) < 0) {
return -1;
}
if (copy_attribute(self, wrapped, &_Py_ID(__qualname__)) < 0) {
return -1;
}
GeneratorWrapper *gw = (GeneratorWrapper *)self;
gw->wrapped = Py_NewRef(wrapped);
gw->isgen = PyGen_CheckExact(wrapped);
return 0;
}
static PyObject *
generatorwrapper_new(PyTypeObject *tp, PyObject *args, PyObject *kwds)
{
// Note: args and kwds can be NULL if we call it ourselves
assert(tp != NULL);
PyObject *self = tp->tp_alloc(tp, 0);
if (self == NULL) {
return PyErr_NoMemory();
}
GeneratorWrapper *gw = (GeneratorWrapper *)self;
gw->isgen = 0;
gw->wrapped = NULL;
return self;
}
static int
generatorwrapper_init(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *wrapped;
if (!PyArg_ParseTuple(args, "O", &wrapped)) {
return -1;
}
return generatorwrapper_fast_init(self, wrapped);
}
static PyObject *
generatorwrapper_fast_new(PyObject *self, PyObject *wrapped)
{
types_state *state = get_module_state(self);
PyTypeObject *tp = (PyTypeObject *)state->_GeneratorWrapper;
assert(tp != NULL);
PyObject *obj = tp->tp_new(tp, NULL, NULL);
if (obj == NULL) {
return NULL;
}
if (generatorwrapper_fast_init(obj, wrapped) < 0) {
Py_DECREF(obj);
return NULL;
}
return obj;
}
static int
generatorwrapper_clear(PyObject *self)
{
GeneratorWrapper *gw = (GeneratorWrapper *)self;
Py_CLEAR(gw->wrapped);
return 0;
}
static int
generatorwrapper_traverse(PyObject *self, visitproc visit, void *arg)
{
GeneratorWrapper *gw = (GeneratorWrapper *)self;
Py_VISIT(gw->wrapped);
return 0;
}
static void
generatorwrapper_dealloc(PyObject *self)
{
if (PyObject_CallFinalizerFromDealloc(self) < 0) {
return;
}
GeneratorWrapper *gw = (GeneratorWrapper *)self;
PyObject_GC_UnTrack(gw);
(void)generatorwrapper_clear(self);
PyTypeObject *tp = Py_TYPE(gw);
tp->tp_free(gw);
Py_DECREF(tp);
}
static PySendResult
generatorwrapper_send(PyObject *self, PyObject *arg, PyObject **result)
{
GeneratorWrapper *gw = (GeneratorWrapper *)self;
PyAsyncMethods *am = Py_TYPE(gw->wrapped)->tp_as_async;
if (am != NULL && am->am_send) {
return am->am_send(gw->wrapped, arg, result);
}
// Slow path: fall back to the send() method
PyObject *yielded = PyObject_CallMethodOneArg(gw->wrapped, &_Py_ID(send), arg);
if (yielded != NULL) {
*result = yielded;
return PYGEN_NEXT;
}
assert(PyErr_Occurred());
PyObject *err = PyErr_GetRaisedException();
assert(err != NULL);
if (PyErr_GivenExceptionMatches(err, PyExc_StopIteration)) {
// XXX Not thread safe?
*result = Py_NewRef(((PyStopIterationObject *)err)->value);
Py_DECREF(err);
return PYGEN_RETURN;
}
PyErr_SetRaisedException(err);
*result = NULL;
return PYGEN_ERROR;
}
static PyObject *
generatorwrapper_next(PyObject *self)
{
GeneratorWrapper *gw = (GeneratorWrapper *)self;
iternextfunc iternext = Py_TYPE(gw->wrapped)->tp_iternext;
if (iternext != NULL) {
return iternext(gw->wrapped);
}
// Slow path: fall back to __iter__()
return PyObject_CallMethodNoArgs(gw->wrapped, &_Py_ID(__iter__));
}
static PyObject *
generatorwrapper_iter(PyObject *self)
{
GeneratorWrapper *gw = (GeneratorWrapper *)self;
if (gw->isgen) {
return Py_NewRef(gw->wrapped);
}
return Py_NewRef(self);
}
/*[clinic input]
@getter
_types._GeneratorWrapper.gi_code
[clinic start generated code]*/
static PyObject *
_types__GeneratorWrapper_gi_code_get_impl(GeneratorWrapper *self)
/*[clinic end generated code: output=2c1b761a19d80282 input=be5ad615362bed63]*/
{
return PyObject_GetAttrString(self->wrapped, "gi_code");
}
/*[clinic input]
@getter
_types._GeneratorWrapper.gi_frame
[clinic start generated code]*/
static PyObject *
_types__GeneratorWrapper_gi_frame_get_impl(GeneratorWrapper *self)
/*[clinic end generated code: output=b162dc70e9d0b41d input=6f0b97a6424fff8f]*/
{
return PyObject_GetAttrString(self->wrapped, "gi_frame");
}
/*[clinic input]
@getter
_types._GeneratorWrapper.gi_running
[clinic start generated code]*/
static PyObject *
_types__GeneratorWrapper_gi_running_get_impl(GeneratorWrapper *self)
/*[clinic end generated code: output=d89bdf92409ca5cf input=8185c689c156d06f]*/
{
return PyObject_GetAttrString(self->wrapped, "gi_running");
}
/*[clinic input]
@getter
_types._GeneratorWrapper.gi_yieldfrom
[clinic start generated code]*/
static PyObject *
_types__GeneratorWrapper_gi_yieldfrom_get_impl(GeneratorWrapper *self)
/*[clinic end generated code: output=37473aae41ca9eb1 input=8c1d1624d55e9d76]*/
{
return PyObject_GetAttrString(self->wrapped, "gi_yieldfrom");
}
// We could get send(), throw(), and close() to work with copy_attribute() in the
// constructor, but that screws up usage of dir()
/*[clinic input]
_types._GeneratorWrapper.send
val: object
[clinic start generated code]*/
static PyObject *
_types__GeneratorWrapper_send_impl(GeneratorWrapper *self, PyObject *val)
/*[clinic end generated code: output=acb9858877ecf82b input=3c530038fae4f727]*/
{
return PyObject_CallMethodOneArg(self->wrapped, &_Py_ID(send), val);
}
static PyObject *
generatorwrapper_throw(PyObject *self, PyObject *args, PyObject *kwds)
{
GeneratorWrapper *gw = (GeneratorWrapper *)self;
PyObject *throw = PyObject_GetAttr(gw->wrapped, &_Py_ID(throw));
if (throw == NULL) {
return NULL;
}
PyObject *res = PyObject_Call(throw, args, kwds);
Py_DECREF(throw);
return res;
}
/*[clinic input]
_types._GeneratorWrapper.close
[clinic start generated code]*/
static PyObject *
_types__GeneratorWrapper_close_impl(GeneratorWrapper *self)
/*[clinic end generated code: output=c8beba19bb976798 input=3bf594a973c58c7b]*/
{
return PyObject_CallMethodNoArgs(self->wrapped, &_Py_ID(close));
}
static PyGetSetDef generatorwrapper_getset[] = {
_TYPES__GENERATORWRAPPER_GI_CODE_GETSETDEF
_TYPES__GENERATORWRAPPER_GI_FRAME_GETSETDEF
_TYPES__GENERATORWRAPPER_GI_RUNNING_GETSETDEF
_TYPES__GENERATORWRAPPER_GI_YIELDFROM_GETSETDEF
{"cr_code", (getter)_types__GeneratorWrapper_gi_code_get},
{"cr_frame", (getter)_types__GeneratorWrapper_gi_frame_get},
{"cr_running", (getter)_types__GeneratorWrapper_gi_running_get},
{"cr_await", (getter)_types__GeneratorWrapper_gi_yieldfrom_get},
{NULL}
};
static PyMethodDef generatorwrapper_methods[] = {
_TYPES__GENERATORWRAPPER_SEND_METHODDEF
{"throw", (PyCFunction)generatorwrapper_throw, METH_VARARGS | METH_KEYWORDS, NULL},
_TYPES__GENERATORWRAPPER_CLOSE_METHODDEF
{NULL}
};
static PyType_Slot GeneratorWrapper_Slots[] = {
{Py_tp_init, generatorwrapper_init},
{Py_tp_traverse, generatorwrapper_traverse},
{Py_tp_clear, generatorwrapper_clear},
{Py_tp_dealloc, generatorwrapper_dealloc},
{Py_am_send, generatorwrapper_send},
{Py_tp_getset, generatorwrapper_getset},
{Py_tp_methods, generatorwrapper_methods},
{Py_tp_iternext, generatorwrapper_next},
{Py_tp_iter, generatorwrapper_iter},
{Py_am_await, generatorwrapper_iter},
{Py_tp_new, generatorwrapper_new},
{0, NULL}
};
PyType_Spec _GeneratorWrapper_Spec = {
.name = "types._GeneratorWrapper",
.basicsize = sizeof(GeneratorWrapper),
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE | Py_TPFLAGS_MANAGED_DICT |
Py_TPFLAGS_MANAGED_DICT | Py_TPFLAGS_MANAGED_WEAKREF,
.slots = GeneratorWrapper_Slots,
};
/*[clinic input]
_types.coroutine
func: object
Convert regular generator function to a coroutine.
[clinic start generated code]*/
static PyObject *
_types_coroutine_impl(PyObject *module, PyObject *func)
/*[clinic end generated code: output=9d829b77b39bfbeb input=b32ba38c90aa4bcf]*/
{
if (!PyCallable_Check(func))
{
PyErr_SetString(PyExc_TypeError, "types.coroutine() expects a callable");
return NULL;
}
if (PyFunction_Check(func))
{
PyCodeObject *code = (PyCodeObject *)PyFunction_GET_CODE(func); // Borrowed
if (code->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))
{
// Already a coroutine function
return Py_NewRef(func);
}
if (code->co_flags & CO_GENERATOR)
{
return generator_as_coroutine(func, code);
}
}
PyObject *transport = PyTuple_New(2);
if (transport == NULL)
{
return NULL;
}
PyTuple_SET_ITEM(transport, 0, Py_NewRef(module));
PyTuple_SET_ITEM(transport, 1, Py_NewRef(func));
PyObject *cfunc = PyCFunction_New((PyMethodDef *)&wrapped_decorator_md, transport);
Py_DECREF(transport);
return cfunc;
}
static int
resolve_bases_lock_held(PyObject *fast_bases, PyObject *new_bases,
PyObject *bases, int *updated)
{
assert(new_bases != NULL);
assert(PyList_CheckExact(new_bases));
Py_ssize_t shift = 0;
Py_ssize_t size = PySequence_Fast_GET_SIZE(fast_bases);
for (Py_ssize_t index = 0; index < size; ++index) {
PyObject *item = PySequence_Fast_GET_ITEM(fast_bases, index);
if (item == NULL) {
return -1;
}
if (PyType_Check(item)) {
continue;
}
PyObject *mro_entries;
if (PyObject_GetOptionalAttr(item, &_Py_ID(__mro_entries__), &mro_entries) < 0) {
return -1;
}
if (mro_entries == NULL) {
continue;
}
*updated = 1;
PyObject *new_base = PyObject_CallOneArg(mro_entries, bases);
Py_DECREF(mro_entries);
if (new_base == NULL) {
return -1;
}
if (!PyTuple_Check(new_base)) {
Py_DECREF(new_base);
PyErr_SetString(PyExc_TypeError,
"__mro_entries__ must return a tuple");
return -1;
}
assert(new_bases != NULL);
if (PyList_SetSlice(new_bases, index + shift, index + shift + 1, new_base) < 0)
{
Py_DECREF(new_base);
return -1;
}
Py_ssize_t new_base_size = PySequence_Size(new_base);
if (new_base_size < 0) {
Py_DECREF(new_base);
return -1;
}
shift += new_base_size - 1;
Py_DECREF(new_base);
}
return 0;
}
/*[clinic input]
_types.resolve_bases
bases: object
Resolve MRO entries dynamically as specified by PEP 560.
[clinic start generated code]*/
static PyObject *
_types_resolve_bases_impl(PyObject *module, PyObject *bases)
/*[clinic end generated code: output=4f8e2e4bfdaeba2e input=84fbb8401697b712]*/
{
if (bases == NULL) {
// For new_class(), we need to handle NULL
return PyTuple_New(0);
}
PyObject *new_bases = PyObject_CallOneArg((PyObject *)&PyList_Type, bases);
if (new_bases == NULL) {
return NULL;
}
PyObject *fast_bases = PySequence_Fast(bases, "bases is not a sequence");
if (fast_bases == NULL) {
Py_DECREF(new_bases);
return NULL;
}
int updated = 0;
int res;
Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(fast_bases);
res = resolve_bases_lock_held(fast_bases, new_bases, bases, &updated);
Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
if (res < 0) {
Py_DECREF(new_bases);
return NULL;
}
if (!updated) {
Py_DECREF(new_bases);
return Py_NewRef(bases);
}
PyObject *result = PyList_AsTuple(new_bases);
Py_DECREF(new_bases);
return result;
}
/*[clinic input]
_types.get_original_bases
cls: object(subclass_of="&PyType_Type")
Return the class's "original" bases prior to modification by `__mro_entries__`.
Examples::
from typing import TypeVar, Generic, NamedTuple, TypedDict
T = TypeVar("T")
class Foo(Generic[T]): ...
class Bar(Foo[int], float): ...
class Baz(list[str]): ...
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
Spam = TypedDict("Spam", {"a": int, "b": str})
assert get_original_bases(Bar) == (Foo[int], float)
assert get_original_bases(Baz) == (list[str],)
assert get_original_bases(Eggs) == (NamedTuple,)
assert get_original_bases(Spam) == (TypedDict,)
assert get_original_bases(int) == (object,)
[clinic start generated code]*/
static PyObject *
_types_get_original_bases_impl(PyObject *module, PyObject *cls)
/*[clinic end generated code: output=f42e23aec2fb73a9 input=30e786bccf62cac8]*/
{
// Apparently, cls.__dict__['__orig_bases__'] can be different from
// cls.__orig_bases__. We want the former.
PyObject *orig_bases;
PyObject *dict = PyObject_GenericGetDict(cls, NULL);
if (dict == NULL) {
return NULL;
}
if (PyDict_GetItemStringRef(dict, "__orig_bases__", &orig_bases) < 0) {
Py_DECREF(dict);
return NULL;
}
Py_DECREF(dict);
if (orig_bases != NULL)
{
return orig_bases;
}
return PyObject_GetAttr(cls, &_Py_ID(__bases__));
}
static PyObject *
calculate_meta_lock_held(PyObject *fast_bases, PyObject *meta)
{
PyObject *winner = meta;
Py_ssize_t length = PySequence_Fast_GET_SIZE(fast_bases);
for (Py_ssize_t i = 0; i < length; ++i) {
PyObject *base = PySequence_Fast_GET_ITEM(fast_bases, i);
PyObject *base_meta = (PyObject *)Py_TYPE(base);
// XXX Speed this up with PyType_IsSubtype()?
int should_continue = PyObject_IsSubclass(winner, base_meta);
if (should_continue < 0) {
return NULL;
}
else if (should_continue) {
continue;
}
int is_new_winner = PyObject_IsSubclass(base_meta, winner);
if (is_new_winner < 0) {
return NULL;
}
else if (is_new_winner) {
winner = base_meta;
continue;
}
PyErr_SetString(PyExc_TypeError,
"metaclass conflict: the metaclass of a derived "
"class must be a (non-strict) subclass "
"of the metaclass of all its bases");
return NULL;
}
return winner;
}
/*[clinic input]
_types._calculate_meta
meta: object(subclass_of="&PyType_Type"),
bases: object
Calculate the most derived metaclass.
[clinic start generated code]*/
static PyObject *
_types__calculate_meta_impl(PyObject *module, PyObject *meta,
PyObject *bases)
/*[clinic end generated code: output=28e8861429963892 input=e9e200da498b891e]*/
{
PyObject *fast_bases = PySequence_Fast(bases, "bases is not a sequence");
if (fast_bases == NULL) {
return NULL;
}
PyObject *winner;
Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(fast_bases);
winner = calculate_meta_lock_held(fast_bases, meta);
Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
Py_DECREF(fast_bases);
if (winner == NULL) {
return NULL;
}
return Py_NewRef(winner);
}
/*[clinic input]
_types.prepare_class
name: str,
bases: object = NULL
kwds: object = NULL
Call the __prepare__ method of the appropriate metaclass.
Returns (metaclass, namespace, kwds) as a 3-tuple
*metaclass* is the appropriate metaclass
*namespace* is the prepared class namespace
*kwds* is an updated copy of the passed in kwds argument with any
'metaclass' entry removed. If no kwds argument is passed in, this will
be an empty dict.
[clinic start generated code]*/
static PyObject *
_types_prepare_class_impl(PyObject *module, const char *name,
PyObject *bases, PyObject *kwds)
/*[clinic end generated code: output=fd787fbe110b28fd input=360e666a1295e075]*/
{
PyObject *meta = NULL;
if (kwds != NULL)
{
kwds = PyDict_Copy(kwds);
if (kwds == NULL) {
return NULL;
}
if (PyDict_Pop(kwds, &_Py_ID(metaclass), &meta) < 0) {
Py_DECREF(kwds);
return NULL;
}
}
if (meta == NULL) {
Py_ssize_t bases_length = PySequence_Size(bases);
if (bases_length == -1) {
Py_XDECREF(kwds);
return NULL;
}
if (bases_length == 0) {
// Immortal reference, but treat it as strong
meta = (PyObject *)&PyType_Type;
}
else {
PyObject *obj = PySequence_GetItem(bases, 0);
if (obj == NULL) {
Py_XDECREF(kwds);
return NULL;
}
meta = Py_NewRef(Py_TYPE(obj));
Py_DECREF(obj);
}
}
assert(meta != NULL);
if (PyType_Check(meta)) {
PyObject *new_meta = _types__calculate_meta_impl(module, meta, bases);
Py_DECREF(meta);
if (new_meta == NULL) {
Py_XDECREF(kwds);
return NULL;
}
meta = new_meta;
}
PyObject *prepare;
if (PyObject_GetOptionalAttr(meta, &_Py_ID(__prepare__), &prepare) < 0) {
Py_DECREF(meta);
Py_XDECREF(kwds);
return NULL;
}
PyObject *name_str = PyUnicode_FromString(name);
if (name_str == NULL) {
Py_DECREF(meta);
Py_XDECREF(kwds);
return NULL;
}
PyObject *namespace;
if (prepare != NULL) {
namespace = PyObject_VectorcallDict(prepare,
(PyObject *[]) { name_str, bases },
2, kwds);
}
else {
namespace = PyDict_New();
}
Py_DECREF(name_str);
if (namespace == NULL) {
Py_DECREF(meta);
Py_XDECREF(kwds);
return NULL;
}
PyObject *final_tuple = PyTuple_New(3);
if (final_tuple == NULL) {
Py_DECREF(meta);
Py_XDECREF(kwds);
Py_DECREF(namespace);
return NULL;
}
// All three of these are stolen by the tuple
PyTuple_SET_ITEM(final_tuple, 0, meta);
PyTuple_SET_ITEM(final_tuple, 1, namespace);
PyTuple_SET_ITEM(final_tuple, 2, kwds);
return final_tuple;
}
/*[clinic input]
_types.new_class
name: str
bases: object = NULL
kwds: object = NULL
exec_body: object = NULL
Create a class object dynamically using the appropriate metaclass.
[clinic start generated code]*/
static PyObject *
_types_new_class_impl(PyObject *module, const char *name, PyObject *bases,
PyObject *kwds, PyObject *exec_body)
/*[clinic end generated code: output=0d1cb5e70abb6971 input=312127772876125b]*/
{
PyObject *resolved_bases = _types_resolve_bases_impl(module, bases);
if (resolved_bases == NULL) {
return NULL;
}
PyObject *prepared_tuple = _types_prepare_class_impl(module, name, resolved_bases, kwds);
if (prepared_tuple == NULL) {
Py_DECREF(resolved_bases);
return NULL;
}
assert(PyTuple_CheckExact(prepared_tuple));
// In theory, no other threads should be able to have this tuple, so
// we don't have to worry about thread safety here.
PyObject *meta = PyTuple_GET_ITEM(prepared_tuple, 0);
PyObject *ns = PyTuple_GET_ITEM(prepared_tuple, 1);
PyObject *prep_kwds = PyTuple_GET_ITEM(prepared_tuple, 2);
if (exec_body != NULL && exec_body != Py_None) {
PyObject *res = PyObject_CallOneArg(exec_body, ns);
Py_XDECREF(res);
if (res == NULL) {
Py_DECREF(resolved_bases);
Py_DECREF(prepared_tuple);
return NULL;
}
}
// bases == NULL will imply that both the bases and resolved bases
// are an empty tuple.
if (bases != NULL && resolved_bases != bases) {
if (PyDict_SetItemString(ns, "__orig_bases__", bases) < 0) {
Py_DECREF(resolved_bases);
Py_DECREF(prepared_tuple);
return NULL;
}
}
PyObject *name_str = PyUnicode_FromString(name);
if (name_str == NULL) {
Py_DECREF(resolved_bases);
Py_DECREF(prepared_tuple);
return NULL;
}
PyObject *cls = PyObject_VectorcallDict(meta,
(PyObject *[]) { name_str, resolved_bases, ns },
3, prep_kwds);
Py_DECREF(name_str);
Py_DECREF(resolved_bases);
Py_DECREF(prepared_tuple);
return cls;
}
struct _DynamicClassAttribute {
PyObject_HEAD;
PyObject *fget;
PyObject *fset;
PyObject *fdel;
PyObject *doc;
int overwrite_doc;
int is_abstract_method;
};
static PyObject *
dynamicclassattribute_new(PyTypeObject *tp, PyObject *args, PyObject *kwds)
{
// Note: args and kwds could be NULL if we initialize it ourselves
PyObject *self = tp->tp_alloc(tp, 0);
if (self == NULL) {
return PyErr_NoMemory();
}
DynamicClassAttribute *dca = (DynamicClassAttribute *)self;
dca->fget = NULL;
dca->fset = NULL;
dca->fdel = NULL;
dca->doc = NULL;
dca->overwrite_doc = 0;
dca->is_abstract_method = 0;
return self;
}
static int
dynamicclassattribute_build(DynamicClassAttribute *dca, PyObject *fget,
PyObject *fset, PyObject *fdel, PyObject *doc)
{
dca->fget = Py_XNewRef(fget);
dca->fset = Py_XNewRef(fset);
dca->fdel = Py_XNewRef(fdel);
PyObject *the_doc = doc == NULL
? PyObject_GetAttr(Py_None, &_Py_ID(__doc__))
: Py_NewRef(doc);
if (the_doc == NULL)
{
return -1;
}
dca->doc = the_doc;
dca->overwrite_doc = doc == NULL;
int is_abstract_method = PyObject_HasAttrStringWithError(fget, "__abstractmethod__");
if (is_abstract_method < 0)
{
return -1;