import typing
import uuid
class MyAnnotation:
def __init__(self, **properties) -> None:
self.properties = properties
def uuid_from_str(s: str) -> uuid.UUID:
return uuid.UUID(f'urn:uuid:{s}')
coercion = typing.Annotated[uuid_from_str, MyAnnotation(type='str', format='uuid')]
coercion('00000000-0000-0000-0000-000000000000')
Traceback (most recent call last):
File "/Users/.../foo.py", line 12, in <module>
coercion('00000000-0000-0000-0000-000000000000')
File "/Users/.../lib/python3.12/typing.py", line 1142, in __call__
result.__orig_class__ = self
^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../lib/python3.12/uuid.py", line 278, in __setattr__
raise TypeError('UUID objects are immutable')
TypeError: UUID objects are immutable
Bug report
Bug description:
typing.Annotatedtries to set an attribute on the return value of calling an annotated callable. This fails when the returned object is immutable. I believe that addingTypeErrorto theexceptclause intyping. _BaseGenericAlias.__call__will fix the problem. I'm not sure if there are more cases of the same pattern or not.cpython/Lib/typing.py
Lines 1128 to 1131 in 17689e3
Example
Result
CPython versions tested on:
3.9, 3.10, 3.11, 3.12
Operating systems tested on:
macOS
Linked PRs
typing.Annotatedfor immutable types (GH-115213) #115227typing.Annotatedfor immutable types (GH-115213) #115228