Skip to content

Conversation

DavidCEllis
Copy link
Contributor

@DavidCEllis DavidCEllis commented Sep 11, 2025

Alternative to #138788 - instead of raising the NotImplementedError this falls back to calling an annotate function with Format.VALUE if both the specified format and Format.VALUE_WITH_FAKE_GLOBALS are both not implemented.

I think this may be more useful behaviour than #138788 ?

If VALUE also fails, then the only option was failure from the start. I think it's more consistent to raise the error from VALUE annotations in that case.

Using the examples from the other PR:

from annotationlib import Format, call_annotate_function

def annotate(format, /):
    if format == Format.VALUE:
        return {'x': str}
    else:
        raise NotImplementedError(format)

print(call_annotate_function(annotate, Format.STRING))

On main, and with this patch:

{'x': 'str'}
from annotationlib import Format, call_annotate_function

def annotate(format, /):
    if format in {Format.VALUE}:
        return {'x': str}
    else:
        raise NotImplementedError(format)

print(call_annotate_function(annotate, Format.STRING))

Main:

TypeError: exceptions must derive from BaseException

Patch:

{'x': 'str'}

@DavidCEllis
Copy link
Contributor Author

I also prefer this over #138788 because I think FORWARDREF and STRING annotations should always work if VALUE annotations work.

@JelleZijlstra
Copy link
Member

I like this too. We might need to extend the listing under https://docs.python.org/3.14/library/annotationlib.html#annotationlib.get_annotations explaining how the different formats work (and in any case, this needs a NEWS entry).

@DavidCEllis
Copy link
Contributor Author

I had a go at extending the descriptions of the formats. This made me realise I was describing behaviour that there wasn't a test for as a fall back so added some extra tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants