Backtestspydanticrun-20261003-150343#12978
mypy [arg-type]-error when passing in type that can be converted to RootModel
The merged fix was judged better than our patch.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches make the same core change. In `add_initializer`, they stop treating `RootModel`'s own hand-written `__init__` as a reason to skip generating the plugin `__init__`. That means `RootModel[float]('1.0')` gets the plugin's untyped (`Any`) signature when `init_typed` is unset, and the `fullname` vs `info.fullname` difference between them is cosmetic. Patch A also registers `pydantic.root_model._RootModelMetaclass` in `get_metaclass_hook`. In `root_model.py`, that class exists only under `TYPE_CHECKING` and is decorated with `dataclass_transform`, so `RootModel` and its subclasses use a different metaclass from `ModelMetaclass`. Without the hook, the plugin never clears that metaclass's `dataclass_transform_spec`. mypy's built-in dataclass_transform handling can then still synthesize or check an `__init__` for `RootModel` classes alongside the pydantic plugin. Patch A closes that gap at its source, which makes root models consistent with how the plugin already handles `BaseModel`. Patch B relies on the plugin-generated `__init__` winning over mypy's dataclass_transform handling, which is less robust. On tests, Patch B is broader: it adds a generic subclass (`Box[T]`), `assert_type` checks, a keyword `root=` call, and an `init_typed=True` module showing errors are kept in strict mode. That is valuable coverage. Patch A extends the existing `root_models.py` fixture and updates the expected outputs for the plugin and non-plugin configs. That directly captures the issue: no error with the plugin, while the non-plugin configs still report errors as expected. Both have tests that fail before the fix. Patch B's test coverage is better, but Patch A's more complete handling of the root-model metaclass makes it the more correct fix overall.
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
9m 6s
Wall-clock time in the container
Full test suite
No new failures
12,253 passed · 503 skipped · 12,756 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
68vs 63 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial 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: unknownThe two patches
pydantic/mypy.pyindex cd28e700..cfdf9d6c 100644@@ -916,7 +916,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` defines an explicit `__init__` for runtime purposes, but its signature should+ # follow the plugin settings (e.g. `init_typed`) like any other model (including its subclasses):+ and self._cls.info.fullname != ROOT_MODEL_FULLNAME+ ): return # Don't generate an __init__ if one already exists typed = self.plugin_config.init_typedtests/mypy/modules/root_models_init.pynew file mode 100644index 00000000..06692ab5@@ -0,0 +1,31 @@+from typing import TypeVar++from typing_extensions import assert_type++from pydantic import RootModel++T = TypeVar('T')++FloatRootModel = RootModel[float]+++class Weight(RootModel[float]):+ pass+++class Box(RootModel[T]):+ pass+++# With `init_typed = False` (the default), the root value can be of any type, as it is validated+# (and possibly coerced) at runtime. `RootModel` itself should behave like its subclasses:+float_root_model = FloatRootModel('1.0')+assert_type(float_root_model.root, float)+assert_type(RootModel[float]('1.0'), RootModel[float])+FloatRootModel(root='1.0')++weight = Weight('1.0')+assert_type(weight.root, float)++box = Box[int]('1')+assert_type(box.root, int)tests/mypy/modules/root_models_init_typed.pynew file mode 100644index 00000000..0d51cdfd@@ -0,0 +1,27 @@+from typing import TypeVar++from pydantic import RootModel++T = TypeVar('T')++FloatRootModel = RootModel[float]+++class Weight(RootModel[float]):+ pass+++class Box(RootModel[T]):+ pass+++# With `init_typed = True`, the root value must match the root type, for `RootModel` itself as well as its subclasses:+FloatRootModel(1.0)+FloatRootModel('1.0') # type: ignore[arg-type]+RootModel[float]('1.0') # type: ignore[arg-type]++Weight(1.0)+Weight('1.0') # type: ignore[arg-type]++Box[int](1)+Box[int]('1') # type: ignore[arg-type]tests/mypy/test_mypy.pyindex c66f1964..cffd6aef 100644@@ -107,6 +107,8 @@ 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.ini', 'root_models_init.py'),+ ('mypy-plugin-strict.ini', 'root_models_init_typed.py'), ('mypy-plugin.ini', 'plugin_strict_fields.py'), ('mypy-plugin.ini', 'final_with_default.py'), ('mypy-plugin.ini', 'create_model_var.py'),
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]