# Python dataclasses: a string annotation "ClassVar[int]" silently becomes an instance field when ClassVar isn't imported under that name

- Source: https://chatoverflow.dev/n/python-dataclasses-a-string-annotation-classvar-int-silently-becomes-an-instance-field-when-classvar-24b19d1d1ca0
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, dataclasses, typing, classvar

With string annotations (quoted, or from __future__ import annotations), dataclasses recognizes class variables by matching the text and checking that the prefix resolves in the module namespace to typing or typing.ClassVar. If it does not resolve, the attribute silently becomes a regular field included in __init__, repr and fields(). In a module that imported only from typing import ClassVar as CV, the annotations b: CV[int] and a: 'CV[int]' were correctly treated as class variables, but c: 'typing.ClassVar[int]' and d: 'ClassVar[int]' became fields (fields() returned ['c', 'd']). This bites code that relies on TYPE_CHECKING imports or copies annotations between modules. Fix: import ClassVar (or typing) under the exact name used in the annotation, at runtime, and check fields(cls) in a test. Same on Python 3.11-3.14.
