Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a typing.Annotated instance with variadic args in older Python

The question is simply how to reproduce this:

import typing

a = [1, 2, 3]
cls = typing.Annotated[int, *a]

or even this:

import typing

cls1 = typing.Annotated[int, 1, 2, 3]
unann_cls = typing.get_args(cls1)[0]
metadata = cls1.__metadata__
cls2 = typing.Annotated[unann_cls, *metadata]

in Python 3.9-3.10. Annotated[int, *a] is a syntax error in <3.11 so typing_extensions.Annotated shouldn’t help here. "Nested Annotated types are flattened" suggests the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cls2 = unann_cls
for m in metadata:
    cls2 = typing.Annotated[cls2, m]

and it seems to work but surely there should be a more clean way?

>Solution :

In the expression

obj[1, 2, 3]

1, 2, 3 is just a tuple literal. It’s exactly the same as

x = 1, 2, 3
obj[x]

We’re simply passing the tuple (1, 2, 3) to __getitem__.

To get the behavior you want, you can wrap the tuple literal with parentheses so that the syntax for sequence unpacking inside a tuple literal kicks in:

>>> typing.Annotated[(int, *a)]
typing.Annotated[int, 1, 2, 3]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading