Skip to content

fix: detect ClassVar wrapped in ForwardRef on Python 3.14#1576

Open
muhamedfazalps wants to merge 1 commit into
python-attrs:mainfrom
muhamedfazalps:fix/forwardref-classvar-detection-314
Open

fix: detect ClassVar wrapped in ForwardRef on Python 3.14#1576
muhamedfazalps wants to merge 1 commit into
python-attrs:mainfrom
muhamedfazalps:fix/forwardref-classvar-detection-314

Conversation

@muhamedfazalps

Copy link
Copy Markdown

Closes #1575

Problem

In Python 3.14, annotations are returned as ForwardRef objects (via annotationlib) instead of plain strings. str(ForwardRef('ClassVar[str]')) produces the repr string "ForwardRef('ClassVar[str]', is_class=True)" which does not match the ClassVar prefix checks in _is_class_var.

When ClassVar is imported under TYPE_CHECKING, the annotation exists as a ForwardRef but goes undetected, causing attrs to treat ClassVar attributes as regular init parameters.

Fix

Extract __forward_arg__ from ForwardRef objects when available, which returns the raw annotation string (e.g. "ClassVar[str]"). Falls back to str(annot) for older Python versions.

If this helps, consider buying me a coffee! https://buymeacoffee.com/muhamedfazalps

Python 3.14 uses annotationlib which returns annotations as
ForwardRef objects instead of plain strings. str(ForwardRef(...))
produces a repr string like 'ForwardRef(...)' which does not
match the ClassVar prefix checks.

Fix by extracting __forward_arg__ from ForwardRef objects when
available, which returns the raw annotation string.

Fixes python-attrs#1575
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

attrs doesn't recognize ClassVar if not imported in Python 3.14

1 participant