Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2e87774

Browse files
authored
bpo-41780: Fix __dir__ of types.GenericAlias (GH-22262)
Automerge-Triggered-By: @gvanrossum
1 parent ac0333e commit 2e87774

3 files changed

Lines changed: 46 additions & 0 deletions

File tree

Lib/test/test_genericalias.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,11 @@ def test_union_generic(self):
287287
self.assertEqual(a.__args__, (list[T], tuple[T, ...]))
288288
self.assertEqual(a.__parameters__, (T,))
289289

290+
def test_dir(self):
291+
dir_of_gen_alias = set(dir(list[int]))
292+
self.assertTrue(dir_of_gen_alias.issuperset(dir(list)))
293+
for generic_alias_property in ("__origin__", "__args__", "__parameters__"):
294+
self.assertIn(generic_alias_property, dir_of_gen_alias)
290295

291296
if __name__ == "__main__":
292297
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :meth:`__dir__` of :class:`types.GenericAlias`. Patch by Batuhan
2+
Taskaya.

Objects/genericaliasobject.c

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,11 +487,50 @@ ga_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
487487
alias->origin, alias->args);
488488
}
489489

490+
static PyObject *
491+
ga_dir(PyObject *self, PyObject *Py_UNUSED(ignored))
492+
{
493+
gaobject *alias = (gaobject *)self;
494+
PyObject *dir = PyObject_Dir(alias->origin);
495+
if (dir == NULL) {
496+
return NULL;
497+
}
498+
499+
PyObject *dir_entry = NULL;
500+
for (const char * const *p = attr_exceptions; ; p++) {
501+
if (*p == NULL) {
502+
break;
503+
}
504+
else {
505+
dir_entry = PyUnicode_FromString(*p);
506+
if (dir_entry == NULL) {
507+
goto error;
508+
}
509+
int contains = PySequence_Contains(dir, dir_entry);
510+
if (contains < 0) {
511+
goto error;
512+
}
513+
if (contains == 0 && PyList_Append(dir, dir_entry) < 0) {
514+
goto error;
515+
}
516+
517+
Py_CLEAR(dir_entry);
518+
}
519+
}
520+
return dir;
521+
522+
error:
523+
Py_DECREF(dir);
524+
Py_XDECREF(dir_entry);
525+
return NULL;
526+
}
527+
490528
static PyMethodDef ga_methods[] = {
491529
{"__mro_entries__", ga_mro_entries, METH_O},
492530
{"__instancecheck__", ga_instancecheck, METH_O},
493531
{"__subclasscheck__", ga_subclasscheck, METH_O},
494532
{"__reduce__", ga_reduce, METH_NOARGS},
533+
{"__dir__", ga_dir, METH_NOARGS},
495534
{0}
496535
};
497536

0 commit comments

Comments
 (0)