@@ -317,40 +317,44 @@ def _get_meta_string(self) -> str | None:
317317
318318 @property
319319 def annotated (self ) -> str | None :
320- """Get Annotated type hint with Meta constraints."""
320+ """Get Annotated type hint with Meta constraints.
321+
322+ For ClassVar fields (discriminator tag_field), ClassVar is required
323+ regardless of use_annotated setting.
324+ """
325+ if self .extras .get ("is_classvar" ):
326+ meta = self ._get_meta_string ()
327+ if self .use_annotated and meta :
328+ annotated_type = f"Annotated[{ self .type_hint } , { meta } ]"
329+ return f"ClassVar[{ annotated_type } ]"
330+ return f"ClassVar[{ self .type_hint } ]"
331+
321332 if not self .use_annotated : # pragma: no cover
322333 return None
323334
324335 meta = self ._get_meta_string ()
325336
326- if not meta and not self . extras . get ( "is_classvar" ) :
337+ if not meta :
327338 return None
328339
329- if not self .required and not self . extras . get ( "is_classvar" ) :
340+ if not self .required :
330341 type_hint = self .data_type .type_hint
331342 annotated_type = f"Annotated[{ type_hint } , { meta } ]"
332343 return get_neither_required_nor_nullable_type (annotated_type , self .data_type .use_union_operator )
333344
334- # Handle ClassVar case (for discriminator fields in msgspec)
335- if self .extras .get ("is_classvar" ):
336- if meta :
337- annotated_type = f"Annotated[{ self .type_hint } , { meta } ]"
338- return f"ClassVar[{ annotated_type } ]"
339- return f"ClassVar[{ self .type_hint } ]"
340-
341345 return f"Annotated[{ self .type_hint } , { meta } ]"
342346
343347 @property
344348 def needs_annotated_import (self ) -> bool :
345349 """Check if this field requires the Annotated import.
346350
347- ClassVar fields without Meta constraints don't need Annotated.
351+ ClassVar fields with Meta need Annotated only when use_annotated is True.
352+ ClassVar fields without Meta don't need Annotated.
348353 """
349354 if not self .annotated :
350355 return False
351- # ClassVar without Meta doesn't use Annotated
352356 if self .extras .get ("is_classvar" ):
353- return self ._get_meta_string () is not None
357+ return self .use_annotated and self . _get_meta_string () is not None
354358 return True
355359
356360 @property
0 commit comments