Skip to content

[3.14] annotationlib - calling get_annotations on instances gets an unexpected error #132261

@DavidCEllis

Description

@DavidCEllis

Bug report

Bug description:

In 3.13, inspect.get_annotations would fail if called on instances and give you a TypeError explaining as much.

In 3.14 if you call annotationlib.get_annotations(inst, format=Format.STRING) on an instance you currently get a more confusing error.

from annotationlib import get_annotations, Format

class Example:
    a: int

ex = Example()

print(get_annotations(ex, format=Format.STRING))
Traceback (most recent call last):
  File "<python-input-8>", line 9, in <module>
    print(get_annotations(ex, format=Format.STRING))
          ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/david/src/cpython/Lib/annotationlib.py", line 719, in get_annotations
    ann = _get_and_call_annotate(obj, format)
  File "/home/david/src/cpython/Lib/annotationlib.py", line 826, in _get_and_call_annotate
    ann = call_annotate_function(annotate, format, owner=obj)
  File "/home/david/src/cpython/Lib/annotationlib.py", line 513, in call_annotate_function
    return annotate(format)
TypeError: Example.__annotate__() takes 1 positional argument but 2 were given

As far as I can tell this appears to be because __annotate__ has turned into a bound method.

You currently only see this if you use Format.STRING due to #125618 masking the issue, as with both other formats if __annotations__ has been created on the class it is used instead of calling __annotate__ and if it doesn't you get an empty dict.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

Labels

3.14bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytopic-typingtype-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions