Backtestspydanticrun-20260930-144322#12978

Issue #12978 Merged fix PR #13441 Run 30 Sep 2026 · run-20260930-144322 pydantic/pydantic

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

Par

Our patch was judged on par with the merged fix.

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

Both patches make the same two code changes in pydantic/mypy.py. First, they register `_RootModelMetaclass` in `get_metaclass_hook`, so mypy's dataclass_transform spec is reset and the plugin handles RootModel classes. Second, they bypass the 'don't generate __init__ if one exists' guard when the class is `pydantic.root_model.RootModel` itself. That lets the plugin-generated `__init__` (untyped unless `init_typed` is set) replace RootModel's hand-written typed `__init__`. This fixes the root cause: `RootModel[float]('1.0')` and its subclasses now follow the same plugin settings as BaseModel fields. The only code difference is `self._cls.info.fullname` (A) versus `self._cls.fullname` (B), which are equivalent for a ClassDef. On tests, both add cases for a parametrized alias (`RootModel[float]`) and a subclass, with expected outputs for all three configs. Under plugin_ini (init_typed unset) there are no errors. Under the default configs the errors remain, so the tests would fail before the change and pass after. A also includes a BaseModel control case (`FloatModel(f='1.0')`) that shows parity with the issue's example. B adds an explanatory comment in the test and a clearer inline comment on why RootModel is excluded. A updates the docstrings. These are cosmetic, offsetting differences; correctness, coverage, and scope are the same.

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

43m 38s24 turns

Wall-clock time in the container

Full test suite

No new failures

12,253 passed · 501 skipped · 12,754 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

87vs 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+82 −5
pydantic/mypy.pyindex cd28e700..1026ecf6 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'@@ -142,8 +143,8 @@ class PydanticPlugin(Plugin):         return None      def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:-        """Update Pydantic `ModelMetaclass` definition."""-        if fullname == MODEL_METACLASS_FULLNAME:+        """Update Pydantic `ModelMetaclass` and `_RootModelMetaclass` definitions."""+        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 _RootModelMetaclass).          Let the plugin handle it. This behavior can be disabled         if 'debug_dataclass_transform' is set to True', for testing purposes.@@ -916,8 +917,14 @@ 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:-            return  # Don't generate an __init__ if one already exists+        if (+            '__init__' in self._cls.info.names+            and not self._cls.info.names['__init__'].plugin_generated+            and self._cls.info.fullname != ROOT_MODEL_FULLNAME+        ):+            # Don't generate an __init__ if one already exists (except for `RootModel` itself,+            # so that the `root` argument follows the plugin settings, as with other model fields)+            return          typed = self.plugin_config.init_typed         model_strict = bool(config.strict)tests/mypy/modules/root_models.pyindex 804d1d43..b6c5b532 100644@@ -46,3 +46,19 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[])  assert_type(m.m1, Maybe[int])+++class FloatModel(BaseModel):+    f: float+++FloatRoot = RootModel[float]+++class SubFloat(RootModel[float]):+    pass+++FloatModel(f='1.0')+FloatRoot('1.0')+SubFloat('1.0')tests/mypy/outputs/mypy-default_ini/root_models.pyindex 01cf5bbb..cc6e3c6d 100644@@ -54,3 +54,22 @@ 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])+++class FloatModel(BaseModel):+    f: float+++FloatRoot = RootModel[float]+++class SubFloat(RootModel[float]):+    pass+++FloatModel(f='1.0')+# MYPY: error: Argument "f" to "FloatModel" has incompatible type "str"; expected "float"  [arg-type]+FloatRoot('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+SubFloat('1.0')+# MYPY: error: Argument 1 to "SubFloat" has incompatible type "str"; expected "float"  [arg-type]tests/mypy/outputs/mypy-plugin_ini/root_models.pyindex 5bb30a04..6835c712 100644@@ -49,3 +49,19 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[])  assert_type(m.m1, Maybe[int])+++class FloatModel(BaseModel):+    f: float+++FloatRoot = RootModel[float]+++class SubFloat(RootModel[float]):+    pass+++FloatModel(f='1.0')+FloatRoot('1.0')+SubFloat('1.0')tests/mypy/outputs/pyproject-default_toml/root_models.pyindex 01cf5bbb..cc6e3c6d 100644@@ -54,3 +54,22 @@ 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])+++class FloatModel(BaseModel):+    f: float+++FloatRoot = RootModel[float]+++class SubFloat(RootModel[float]):+    pass+++FloatModel(f='1.0')+# MYPY: error: Argument "f" to "FloatModel" has incompatible type "str"; expected "float"  [arg-type]+FloatRoot('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float"  [arg-type]+SubFloat('1.0')+# MYPY: error: Argument 1 to "SubFloat" has incompatible type "str"; expected "float"  [arg-type] 
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] 

What the agent reported

I fixed this in the mypy plugin (pydantic/mypy.py). With the plugin on, RootModel[float]("1.0") now type-checks the same way Foo(f="1.0") does. A new regression test fails without the fix and passes with it. None of this is committed.

What was wrong. With the plugin's default settings, it gives model constructors Any-typed arguments, which is why Foo(f="1.0") is accepted. Two things kept RootModel from getting the same treatment:

  1. Direct use, RootModel[float](...): RootModel has its own __init__(self, /, root: RootModelRootType = ...). The plugin never replaces an existing __init__, so mypy always checked root against float.
  2. Subclasses, class Sub(RootModel[float]): these hit the same error. RootModel uses a special type-checking-only metaclass that carries its own @dataclass_transform. The plugin switches that off on the normal model metaclass but not on this one. So mypy's own dataclass handling built a strictly typed __init__(self, root: float) for subclasses.

Without the plugin, mypy rejects all three calls, including Foo(f="1.0"). That is already consistent, so I left that mode alone.

What I changed.

  • Added ROOT_MODEL_METACLASS_FULLNAME = 'pydantic.root_model._RootModelMetaclass'. get_metaclass_hook now switches off dataclass_transform for it too, just as it already did for the normal metaclass.
  • add_initializer now also generates __init__ for RootModel itself. So root is Any by default, and typed when init_typed = True or the model is strict, like any other field.
  • Tests: I added the report's scenario (a BaseModel with a float field, RootModel[float], and a RootModel[float] subclass, each called with '1.0') to tests/mypy/modules/root_models.py. I updated the expected outputs:
  • mypy-plugin_ini: no errors on those lines.
  • mypy-default_ini and pyproject-default_toml (no plugin): all three lines error, which is what happens today.

Test evidence.

  • mypy isn't installed in the project environment and installing packages was blocked, so ./bt-test skips all 53 mypy tests. I ran them with the locked version (mypy 1.18.2) taken from the local uv cache through PYTHONPATH, using pytest tests/mypy --test-mypy.
  • Without the fix: the new mypy-plugin.ini / root_models.py test fails, and the only difference is the two RootModel / subclass arg-type errors. The two no-plugin configurations pass.
  • With the fix: 48 passed, 5 failed. Those same 5 also fail on the untouched checkout: pydantic_settings.py under four configurations and strict_equality.py.
  • By hand, I confirmed that init_typed = True and strict=True still report the error, and that results without the plugin are unchanged.
  • ./bt-test tests/test_root_model.py tests/mypy: 78 passed, 53 skipped.

Side effects. Only mypy's view of RootModel changes; runtime and pyright are unaffected. One edge case gets stricter: with init_forbid_extra = True, calling RootModel[dict[str, int]](a=1) directly is now rejected, even though it works at runtime. Subclasses already behaved this way. No test covers that case, or the init_typed = True case; I checked the latter by hand but didn't add a test for it.

Requirements:

  1. Passing a convertible value to RootModel[float] should not raise [arg-type] under mypy: done when the plugin is on. Covered by the regression test above.
  2. BaseModel fields and the RootModel root should behave the same: done for plugin mode, and it now includes RootModel subclasses, which had the same bug. Without the plugin they already matched, since both error; the test outputs for that mode show this.
  3. The same should hold with or without --strict: this flag didn't affect the result either way. With the plugin, the Any typing follows init_typed and each model's own strict setting, the same as for BaseModel fields.