Backtestspydanticrun-20261013-104308#12978

Issue #12978 Merged fix PR #13441 Run 13 Oct 2026 · run-20261013-104308 pydantic/pydantic

mypy [arg-type]-error when passing in type that can be converted to RootModel

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches make the same core fix. They register `_RootModelMetaclass` with the metaclass hook so the plugin, not dataclass_transform, governs RootModel subclasses. They also stop the plugin from deferring to the hand-written typed `__init__` on `RootModel` itself, which is the root cause of `RootModel[float]('1.0')` erroring when `init_typed` is off.

Patch A removes the skip guard when the class is `RootModel`. The generic `add_initializer` path then regenerates `RootModel.__init__` through field collection on a class whose root type is a TypeVar. That probably works, but it is implicit and also replaces the declared signature in typed mode.

Patch B handles `RootModel` explicitly. It leaves the declared typed `__init__` alone when `init_typed` is true. When it is false, it installs a clear `root: Any = ..., **data: Any` signature that mirrors the runtime. This is a narrower, more predictable change.

On tests, Patch B is clearly stronger. It covers:
- the alias case
- direct `RootModel[float](...)` calls
- keyword `root=` usage
- Optional root types
- dict roots with `**data`
- subclasses
- `assert_type` checks that the root type is preserved
- a strict (`init_typed`) config, confirming that typed mode still reports errors

Patch A tests only the positional alias and subclass cases under the default and plugin configs.

Patch B also makes `root` positional-required when it has no default. That is extra scope and slightly risky, but it matches runtime behavior (validation fails without `root`) and is covered by tests. Overall, B's explicit handling and broader verification make it the better fix.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

41m 57s

Wall-clock time in the container

Full test suite

No new failures

0 passed · 54 skipped · 54 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

263vs 63 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

The below example code (named foo.py) passes when running python foo.py as the input "1.0"-string gets converted to float. However, running mypy foo.py (with or without --strict) gives the following error:

foo.py:11: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

I would expect the BaseModel-fields and the RootModel-field to behave the same in this case. That is, if the value can be converted – either via a custom made validator or through the conversion table – then mypy should not raise an error.

Example Code

import pydantic


class Foo(pydantic.BaseModel):
    f: float


RFoo = pydantic.RootModel[float]

f = Foo(f="1.0")
rf = RFoo("1.0")

assert isinstance(f.f, float)
assert isinstance(rf.root, float)
assert f.f == rf.root

Python, Pydantic & OS Version

pydantic version: 2.12.5
        pydantic-core version: 2.41.5
          pydantic-core build: profile=release pgo=false
               python version: 3.11.14 (main, Feb  3 2026, 22:51:56) [Clang 21.1.4 ]
                     platform: Linux-5.15.0-173-generic-x86_64-with-glibc2.35
             related packages: typing_extensions-4.15.0 mypy-1.19.1
                       commit: unknown

The two patches

Our patch+259 −4
pydantic/mypy.pyindex cd28e700..4c9e8064 100644@@ -88,6 +88,7 @@ CREATE_MODEL_FULLNAME = 'pydantic.main.create_model' BASESETTINGS_FULLNAME = 'pydantic_settings.main.BaseSettings' ROOT_MODEL_FULLNAME = 'pydantic.root_model.RootModel' MODEL_METACLASS_FULLNAME = 'pydantic._internal._model_construction.ModelMetaclass'+ROOT_MODEL_METACLASS_FULLNAME = 'pydantic.root_model._RootModelMetaclass' FIELD_FULLNAME = 'pydantic.fields.Field' DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass' MODEL_VALIDATOR_FULLNAME = 'pydantic.functional_validators.model_validator'@@ -143,7 +144,7 @@ class PydanticPlugin(Plugin):      def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:         """Update Pydantic `ModelMetaclass` definition."""-        if fullname == MODEL_METACLASS_FULLNAME:+        if fullname in (MODEL_METACLASS_FULLNAME, ROOT_MODEL_METACLASS_FULLNAME):             return self._pydantic_model_metaclass_marker_callback         return None @@ -171,7 +172,7 @@ class PydanticPlugin(Plugin):         transformer.transform()      def _pydantic_model_metaclass_marker_callback(self, ctx: ClassDefContext) -> None:-        """Reset dataclass_transform_spec attribute of ModelMetaclass.+        """Reset dataclass_transform_spec attribute of ModelMetaclass (and of the `RootModel` metaclass).          Let the plugin handle it. This behavior can be disabled         if 'debug_dataclass_transform' is set to True', for testing purposes.@@ -361,7 +362,7 @@ class PydanticModelField:             variable=variable,             type_annotation=type_annotation,             initializer=None,-            kind=ARG_OPT+            kind=(ARG_OPT if force_optional or self.has_default else ARG_POS)             if is_root_model_root             else (ARG_NAMED_OPT if force_optional or self.has_default else ARG_NAMED),         )@@ -916,10 +917,19 @@ class PydanticModelTransformer:          The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings.         """+        typed = self.plugin_config.init_typed++        if self._cls.info.fullname == ROOT_MODEL_FULLNAME:+            # `RootModel` itself defines an `__init__` with a typed `root` argument. It is used when the class+            # is not subclassed (e.g. `RootModel[int]('1')` or `IntRoot = RootModel[int]; IntRoot('1')`),+            # so it has to follow the `init_typed` setting, like the generated `__init__` of subclasses:+            if not typed:+                self.add_untyped_root_model_initializer()+            return+         if '__init__' in self._cls.info.names and not self._cls.info.names['__init__'].plugin_generated:             return  # Don't generate an __init__ if one already exists -        typed = self.plugin_config.init_typed         model_strict = bool(config.strict)         use_alias = not (config.validate_by_name or config.populate_by_name) and config.validate_by_alias is not False         requires_dynamic_aliases = bool(config.has_alias_generator and not config.validate_by_name)@@ -966,6 +976,17 @@ class PydanticModelTransformer:          add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType()) +    def add_untyped_root_model_initializer(self) -> None:+        """Replaces the `__init__` signature of `RootModel` with one accepting `Any` for the root value.++        This mirrors the runtime signature (`__init__(self, /, root=PydanticUndefined, **data)`).+        """+        args = [+            Argument(Var('root', AnyType(TypeOfAny.special_form)), AnyType(TypeOfAny.special_form), None, ARG_OPT),+            Argument(Var('data', AnyType(TypeOfAny.special_form)), AnyType(TypeOfAny.special_form), None, ARG_STAR2),+        ]+        add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType())+     def add_model_construct_method(         self,         fields: list[PydanticModelField],tests/mypy/modules/root_models.pyindex 804d1d43..d7734b1b 100644@@ -46,3 +46,35 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[])  assert_type(m.m1, Maybe[int])+++# Values that can be validated into the root type are accepted when `init_typed` is disabled,+# the same way as for fields of a `BaseModel`:+FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+    pass+++float_root_model = FloatRootModel('1.0')+float_root_model_kw = FloatRootModel(root='1.0')+float_root_model_direct = RootModel[float]('1.0')+float_root_model_subclass = FloatRootModelSubclass('1.0')+float_root_model_subclass_kw = FloatRootModelSubclass(root='1.0')+optional_int_root_model = RootModel[int | None](root='1')+dict_root_model = RootModel[dict[str, int]](a='1')++assert_type(float_root_model, RootModel[float])+assert_type(float_root_model.root, float)+assert_type(float_root_model_direct.root, float)+assert_type(float_root_model_subclass.root, float)+++class Pets5(RootModel[list[str]]):+    root: list[str] = []+++# `root` is required when it has no default:+Pets1()+Pets5()tests/mypy/outputs/mypy-default_ini/root_models.pyindex 01cf5bbb..731868d1 100644@@ -54,3 +54,42 @@ Model(m1=None, m2={}, m3=[]) # MYPY: error: Argument "m3" to "Model" has incompatible type "list[Never]"; expected "Maybe[Any]"  [arg-type]  assert_type(m.m1, Maybe[int])+++# Values that can be validated into the root type are accepted when `init_typed` is disabled,+# the same way as for fields of a `BaseModel`:+FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+    pass+++float_root_model = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_kw = FloatRootModel(root='1.0')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_direct = RootModel[float]('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_subclass = FloatRootModelSubclass('1.0')+# MYPY: error: Argument 1 to "FloatRootModelSubclass" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_subclass_kw = FloatRootModelSubclass(root='1.0')+# MYPY: error: Argument "root" to "FloatRootModelSubclass" has incompatible type "str"; expected "float"  [arg-type]+optional_int_root_model = RootModel[int | None](root='1')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "int | None"  [arg-type]+dict_root_model = RootModel[dict[str, int]](a='1')++assert_type(float_root_model, RootModel[float])+assert_type(float_root_model.root, float)+assert_type(float_root_model_direct.root, float)+assert_type(float_root_model_subclass.root, float)+++class Pets5(RootModel[list[str]]):+    root: list[str] = []+++# `root` is required when it has no default:+Pets1()+# MYPY: error: Missing positional argument "root" in call to "Pets1"  [call-arg]+Pets5()tests/mypy/outputs/mypy-plugin-strict_ini/root_models.pynew file mode 100644index 00000000..b716acad@@ -0,0 +1,90 @@+from typing import Generic, TypeVar++from typing_extensions import assert_type++from pydantic import BaseModel, RootModel+++class Pets1(RootModel[list[str]]):+    pass+++pets_construct = Pets1.model_construct(['dog'])++Pets2 = RootModel[list[str]]+++class Pets3(RootModel):+# MYPY: error: Missing type parameters for generic type "RootModel"  [type-arg]+    root: list[str]+++pets1 = Pets1(['dog', 'cat'])+pets2 = Pets2(['dog', 'cat'])+pets3 = Pets3(['dog', 'cat'])+++class Pets4(RootModel[list[str]]):+    pets: list[str]+# MYPY: error: Only `root` is allowed as a field of a `RootModel`  [pydantic-field]+++T = TypeVar('T')+V = TypeVar('V')+++class Maybe(RootModel[T | None]):+    pass+++class Model(BaseModel, Generic[V]):+    m1: Maybe[int]+    m2: Maybe[V]+    m3: Maybe+# MYPY: error: Missing type parameters for generic type "Maybe"  [type-arg]+++Model[str](m1=1, m2='dog', m3=[])+m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([]))+Model(m1=None, m2={}, m3=[])++assert_type(m.m1, Maybe[int])+++# Values that can be validated into the root type are accepted when `init_typed` is disabled,+# the same way as for fields of a `BaseModel`:+FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+    pass+++float_root_model = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_kw = FloatRootModel(root='1.0')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_direct = RootModel[float]('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_subclass = FloatRootModelSubclass('1.0')+# MYPY: error: Argument 1 to "FloatRootModelSubclass" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_subclass_kw = FloatRootModelSubclass(root='1.0')+# MYPY: error: Argument "root" to "FloatRootModelSubclass" has incompatible type "str"; expected "float"  [arg-type]+optional_int_root_model = RootModel[int | None](root='1')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "int | None"  [arg-type]+dict_root_model = RootModel[dict[str, int]](a='1')++assert_type(float_root_model, RootModel[float])+assert_type(float_root_model.root, float)+assert_type(float_root_model_direct.root, float)+assert_type(float_root_model_subclass.root, float)+++class Pets5(RootModel[list[str]]):+    root: list[str] = []+++# `root` is required when it has no default:+Pets1()+# MYPY: error: Missing positional argument "root" in call to "Pets1"  [call-arg]+Pets5()tests/mypy/outputs/mypy-plugin_ini/root_models.pyindex 5bb30a04..38f1be53 100644@@ -49,3 +49,36 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[])  assert_type(m.m1, Maybe[int])+++# Values that can be validated into the root type are accepted when `init_typed` is disabled,+# the same way as for fields of a `BaseModel`:+FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+    pass+++float_root_model = FloatRootModel('1.0')+float_root_model_kw = FloatRootModel(root='1.0')+float_root_model_direct = RootModel[float]('1.0')+float_root_model_subclass = FloatRootModelSubclass('1.0')+float_root_model_subclass_kw = FloatRootModelSubclass(root='1.0')+optional_int_root_model = RootModel[int | None](root='1')+dict_root_model = RootModel[dict[str, int]](a='1')++assert_type(float_root_model, RootModel[float])+assert_type(float_root_model.root, float)+assert_type(float_root_model_direct.root, float)+assert_type(float_root_model_subclass.root, float)+++class Pets5(RootModel[list[str]]):+    root: list[str] = []+++# `root` is required when it has no default:+Pets1()+# MYPY: error: Missing positional argument "root" in call to "Pets1"  [call-arg]+Pets5()tests/mypy/outputs/pyproject-default_toml/root_models.pyindex 01cf5bbb..731868d1 100644@@ -54,3 +54,42 @@ Model(m1=None, m2={}, m3=[]) # MYPY: error: Argument "m3" to "Model" has incompatible type "list[Never]"; expected "Maybe[Any]"  [arg-type]  assert_type(m.m1, Maybe[int])+++# Values that can be validated into the root type are accepted when `init_typed` is disabled,+# the same way as for fields of a `BaseModel`:+FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+    pass+++float_root_model = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_kw = FloatRootModel(root='1.0')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_direct = RootModel[float]('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_subclass = FloatRootModelSubclass('1.0')+# MYPY: error: Argument 1 to "FloatRootModelSubclass" has incompatible type "str"; expected "float"  [arg-type]+float_root_model_subclass_kw = FloatRootModelSubclass(root='1.0')+# MYPY: error: Argument "root" to "FloatRootModelSubclass" has incompatible type "str"; expected "float"  [arg-type]+optional_int_root_model = RootModel[int | None](root='1')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "int | None"  [arg-type]+dict_root_model = RootModel[dict[str, int]](a='1')++assert_type(float_root_model, RootModel[float])+assert_type(float_root_model.root, float)+assert_type(float_root_model_direct.root, float)+assert_type(float_root_model_subclass.root, float)+++class Pets5(RootModel[list[str]]):+    root: list[str] = []+++# `root` is required when it has no default:+Pets1()+# MYPY: error: Missing positional argument "root" in call to "Pets1"  [call-arg]+Pets5()tests/mypy/test_mypy.pyindex c66f1964..743013ad 100644@@ -107,6 +107,7 @@ cases: list[ParameterSet | tuple[str, str]] = [         ('mypy-plugin.ini', 'plugin_optional_inheritance.py'),         ('mypy-plugin.ini', 'generics.py'),         ('mypy-plugin.ini', 'root_models.py'),+        ('mypy-plugin-strict.ini', 'root_models.py'),         ('mypy-plugin.ini', 'plugin_strict_fields.py'),         ('mypy-plugin.ini', 'final_with_default.py'),         ('mypy-plugin.ini', 'create_model_var.py'), 
Merged fix · PR #13441+61 −2
pydantic/mypy.pyindex cd28e7004..40aee0627 100644@@ -88,6 +88,7 @@ CREATE_MODEL_FULLNAME = 'pydantic.main.create_model' BASESETTINGS_FULLNAME = 'pydantic_settings.main.BaseSettings' ROOT_MODEL_FULLNAME = 'pydantic.root_model.RootModel' MODEL_METACLASS_FULLNAME = 'pydantic._internal._model_construction.ModelMetaclass'+ROOT_MODEL_METACLASS_FULLNAME = 'pydantic.root_model._RootModelMetaclass' FIELD_FULLNAME = 'pydantic.fields.Field' DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass' MODEL_VALIDATOR_FULLNAME = 'pydantic.functional_validators.model_validator'@@ -143,7 +144,7 @@ class PydanticPlugin(Plugin):      def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:         """Update Pydantic `ModelMetaclass` definition."""-        if fullname == MODEL_METACLASS_FULLNAME:+        if fullname in (MODEL_METACLASS_FULLNAME, ROOT_MODEL_METACLASS_FULLNAME):             return self._pydantic_model_metaclass_marker_callback         return None @@ -916,7 +917,13 @@ class PydanticModelTransformer:          The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings.         """-        if '__init__' in self._cls.info.names and not self._cls.info.names['__init__'].plugin_generated:+        if (+            '__init__' in self._cls.info.names+            and not self._cls.info.names['__init__'].plugin_generated+            # `RootModel` declares a typed `__init__` for the benefit of type checkers when the plugin+            # isn't used, but the plugin-generated one should take priority over it:+            and self._cls.fullname != ROOT_MODEL_FULLNAME+        ):             return  # Don't generate an __init__ if one already exists          typed = self.plugin_config.init_typedtests/mypy/modules/root_models.pyindex 804d1d43e..f95bd7fe1 100644@@ -22,6 +22,18 @@ pets1 = Pets1(['dog', 'cat']) pets2 = Pets2(['dog', 'cat']) pets3 = Pets3(['dog', 'cat']) +RFloat = RootModel[float]+++class RFloatSub(RootModel[float]):+    pass+++# When the plugin is used with `init_typed` unset, arbitrary input+# should be accepted as it may be coerced to the `root` type:+rfloat = RFloat('1.0')+rfloat_sub = RFloatSub('1.0')+  class Pets4(RootModel[list[str]]):     pets: list[str]tests/mypy/outputs/mypy-default_ini/root_models.pyindex 01cf5bbb3..df3354187 100644@@ -23,6 +23,20 @@ pets1 = Pets1(['dog', 'cat']) pets2 = Pets2(['dog', 'cat']) pets3 = Pets3(['dog', 'cat']) +RFloat = RootModel[float]+++class RFloatSub(RootModel[float]):+    pass+++# When the plugin is used with `init_typed` unset, arbitrary input+# should be accepted as it may be coerced to the `root` type:+rfloat = RFloat('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+rfloat_sub = RFloatSub('1.0')+# MYPY: error: Argument 1 to "RFloatSub" has incompatible type "str"; expected "float"  [arg-type]+  class Pets4(RootModel[list[str]]):     pets: list[str]tests/mypy/outputs/mypy-plugin_ini/root_models.pyindex 5bb30a044..12b4c84bd 100644@@ -23,6 +23,18 @@ pets1 = Pets1(['dog', 'cat']) pets2 = Pets2(['dog', 'cat']) pets3 = Pets3(['dog', 'cat']) +RFloat = RootModel[float]+++class RFloatSub(RootModel[float]):+    pass+++# When the plugin is used with `init_typed` unset, arbitrary input+# should be accepted as it may be coerced to the `root` type:+rfloat = RFloat('1.0')+rfloat_sub = RFloatSub('1.0')+  class Pets4(RootModel[list[str]]):     pets: list[str]tests/mypy/outputs/pyproject-default_toml/root_models.pyindex 01cf5bbb3..df3354187 100644@@ -23,6 +23,20 @@ pets1 = Pets1(['dog', 'cat']) pets2 = Pets2(['dog', 'cat']) pets3 = Pets3(['dog', 'cat']) +RFloat = RootModel[float]+++class RFloatSub(RootModel[float]):+    pass+++# When the plugin is used with `init_typed` unset, arbitrary input+# should be accepted as it may be coerced to the `root` type:+rfloat = RFloat('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+rfloat_sub = RFloatSub('1.0')+# MYPY: error: Argument 1 to "RFloatSub" has incompatible type "str"; expected "float"  [arg-type]+  class Pets4(RootModel[list[str]]):     pets: list[str]