Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 52 additions & 38 deletions Lib/test/test_genericalias.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
from dataclasses import Field
from functools import partial, partialmethod, cached_property
from mailbox import Mailbox, _PartialFile
from ctypes import Array, LibraryLoader
try:
import ctypes
except ImportError:
ctypes = None
from difflib import SequenceMatcher
from filecmp import dircmp
from fileinput import FileInput
Expand Down Expand Up @@ -44,45 +47,46 @@

class BaseTest(unittest.TestCase):
"""Test basics."""
generic_types = [type, tuple, list, dict, set, frozenset, enumerate,
defaultdict, deque,
SequenceMatcher,
dircmp,
FileInput,
OrderedDict, Counter, UserDict, UserList,
Pattern, Match,
partial, partialmethod, cached_property,
AbstractContextManager, AbstractAsyncContextManager,
Awaitable, Coroutine,
AsyncIterable, AsyncIterator,
AsyncGenerator, Generator,
Iterable, Iterator,
Reversible,
Container, Collection,
Callable,
Mailbox, _PartialFile,
ContextVar, Token,
Field,
Set, MutableSet,
Mapping, MutableMapping, MappingView,
KeysView, ItemsView, ValuesView,
Sequence, MutableSequence,
MappingProxyType, AsyncGeneratorType,
DirEntry,
chain,
TemporaryDirectory, SpooledTemporaryFile,
Queue, SimpleQueue,
_AssertRaisesContext,
SplitResult, ParseResult,
ValueProxy, ApplyResult,
WeakSet, ReferenceType, ref,
ShareableList, MPSimpleQueue,
Future, _WorkItem,
Morsel]
if ctypes is not None:
generic_types.extend((ctypes.Array, ctypes.LibraryLoader))

def test_subscriptable(self):
for t in (type, tuple, list, dict, set, frozenset, enumerate,
defaultdict, deque,
SequenceMatcher,
dircmp,
FileInput,
OrderedDict, Counter, UserDict, UserList,
Pattern, Match,
partial, partialmethod, cached_property,
AbstractContextManager, AbstractAsyncContextManager,
Awaitable, Coroutine,
AsyncIterable, AsyncIterator,
AsyncGenerator, Generator,
Iterable, Iterator,
Reversible,
Container, Collection,
Callable,
Mailbox, _PartialFile,
ContextVar, Token,
Field,
Set, MutableSet,
Mapping, MutableMapping, MappingView,
KeysView, ItemsView, ValuesView,
Sequence, MutableSequence,
MappingProxyType, AsyncGeneratorType,
DirEntry,
chain,
TemporaryDirectory, SpooledTemporaryFile,
Queue, SimpleQueue,
_AssertRaisesContext,
Array, LibraryLoader,
SplitResult, ParseResult,
ValueProxy, ApplyResult,
WeakSet, ReferenceType, ref,
ShareableList, MPSimpleQueue,
Future, _WorkItem,
Morsel,
):
for t in self.generic_types:
if t is None:
continue
tname = t.__name__
Expand Down Expand Up @@ -289,5 +293,15 @@ def test_dir(self):
for generic_alias_property in ("__origin__", "__args__", "__parameters__"):
self.assertIn(generic_alias_property, dir_of_gen_alias)

def test_weakref(self):
for t in self.generic_types:
if t is None:
continue
tname = t.__name__
with self.subTest(f"Testing {tname}"):
alias = t[int]
self.assertEqual(ref(alias)(), alias)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:class:`types.GenericAlias` objects can now be the targets of weakrefs.
6 changes: 6 additions & 0 deletions Objects/genericaliasobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ typedef struct {
PyObject *origin;
PyObject *args;
PyObject *parameters;
PyObject* weakreflist;
} gaobject;

static void
Expand All @@ -17,6 +18,9 @@ ga_dealloc(PyObject *self)
gaobject *alias = (gaobject *)self;

_PyObject_GC_UNTRACK(self);
if (alias->weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject *)alias);
}
Py_XDECREF(alias->origin);
Py_XDECREF(alias->args);
Py_XDECREF(alias->parameters);
Expand Down Expand Up @@ -593,6 +597,7 @@ PyTypeObject Py_GenericAliasType = {
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = ga_traverse,
.tp_richcompare = ga_richcompare,
.tp_weaklistoffset = offsetof(gaobject, weakreflist),
.tp_methods = ga_methods,
.tp_members = ga_members,
.tp_alloc = PyType_GenericAlloc,
Expand Down Expand Up @@ -624,6 +629,7 @@ Py_GenericAlias(PyObject *origin, PyObject *args)
alias->origin = origin;
alias->args = args;
alias->parameters = NULL;
alias->weakreflist = NULL;
_PyObject_GC_TRACK(alias);
return (PyObject *)alias;
}