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

Skip to content

[3.10] bpo-44662: Add ability to annotate types.Union (GH-27214) #27461

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 30, 2021
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
10 changes: 10 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3009,6 +3009,16 @@ def barfoo3(x: BA2): ...
get_type_hints(barfoo3, globals(), locals(), include_extras=True)["x"],
BA2
)
BA3 = typing.Annotated[int | float, "const"]
def barfoo4(x: BA3): ...
self.assertEqual(
get_type_hints(barfoo4, globals(), locals()),
{"x": int | float}
)
self.assertEqual(
get_type_hints(barfoo4, globals(), locals(), include_extras=True),
{"x": typing.Annotated[int | float, "const"]}
)

def test_get_type_hints_annotated_refs(self):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Add ``__module__`` to ``types.Union``. This also fixes
``types.Union`` issues with ``typing.Annotated``. Patch provided by
Yurii Karabas.
24 changes: 23 additions & 1 deletion Objects/unionobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,28 @@ static PyNumberMethods union_as_number = {
.nb_or = _Py_union_type_or, // Add __or__ function
};

static const char* const cls_attrs[] = {
"__module__", // Required for compatibility with typing module
NULL,
};

static PyObject *
union_getattro(PyObject *self, PyObject *name)
{
unionobject *alias = (unionobject *)self;
if (PyUnicode_Check(name)) {
for (const char * const *p = cls_attrs; ; p++) {
if (*p == NULL) {
break;
}
if (_PyUnicode_EqualToASCIIString(name, *p)) {
return PyObject_GetAttr((PyObject *) Py_TYPE(alias), name);
}
}
}
return PyObject_GenericGetAttr(self, name);
}

PyTypeObject _PyUnion_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
.tp_name = "types.UnionType",
Expand All @@ -435,7 +457,7 @@ PyTypeObject _PyUnion_Type = {
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = union_traverse,
.tp_hash = union_hash,
.tp_getattro = PyObject_GenericGetAttr,
.tp_getattro = union_getattro,
.tp_members = union_members,
.tp_methods = union_methods,
.tp_richcompare = union_richcompare,
Expand Down