Backtestspydanticrun-20261007-130130#12978
mypy [arg-type]-error when passing in type that can be converted to RootModel
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches register `_RootModelMetaclass` in `get_metaclass_hook`, so both fix the subclass case. They differ in how they handle a `RootModel[float]` type alias.
Patch A adds a `get_function_signature_hook` for `RootModel` calls. When `init_typed` is unset, it replaces the `root` argument type with `Any`, so `RFoo('1.0')` passes both positionally and by keyword. It skips generic signatures, so a bare `RootModel(1)` still infers `RootModel[int]`. The change is narrow and leaves `RootModel`'s own class definition alone. The default `init_typed` behaviour is kept, and the docs note the new behaviour. Its tests cover:
- the alias called positionally and by keyword,
- the subclass,
- `assert_type` on `.root`,
- that bare `RootModel(1)` still infers `int`,
- the strict and default configurations producing the expected errors.
Patch B removes the guard that stops the plugin from replacing the explicitly declared `__init__` on `RootModel` itself. `RootModel` then gets a plugin-synthesized `__init__` whose `root` parameter is untyped (`Any`) by default. That fixes the alias case, but it likely breaks generic inference for unparametrized `RootModel(x)`, which would now produce `RootModel[Any]`. It also swaps the hand-written signature, including its `PydanticUndefined` default and `**data` handling, for a synthesized one, which is a broader and riskier change. Its tests do not check that inference is preserved or that the keyword form works.
Patch A is the more targeted and safer fix, and its tests are more thorough.
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
14m 49s
Wall-clock time in the container
Full test suite
No new failures
12,253 passed · 504 skipped · 12,757 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
111vs 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
docs/integrations/mypy.mdindex bf76f18a..66097545 100644@@ -175,6 +175,8 @@ Model(a='1') For this reason, the plugin will use [`Any`][typing.Any] for field annotations when synthesizing the `__init__()` method, unless `init_typed` is set or [strict mode](../concepts/strict_mode.md) is enabled on the model.+This also applies to the `root` argument of a parametrized [`RootModel`][pydantic.RootModel] instantiated+through a type alias (e.g. `IntRoot = RootModel[int]`, then `IntRoot('1')`). ### `init_forbid_extra` pydantic/mypy.pyindex cd28e700..2e42ef9a 100644@@ -49,6 +49,7 @@ from mypy.plugin import ( CheckerPluginInterface, ClassDefContext, DynamicClassDefContext,+ FunctionSigContext, MethodContext, Plugin, ReportConfigContext,@@ -65,6 +66,7 @@ from mypy.typeops import map_type_from_supertype from mypy.types import ( AnyType, CallableType,+ FunctionLike, Instance, NoneType, Type,@@ -88,6 +90,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,10 +146,20 @@ 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 + def get_function_signature_hook(self, fullname: str) -> Callable[[FunctionSigContext], FunctionLike] | None:+ """Adjust the signature of `RootModel` instantiations through a type alias (e.g. `Alias = RootModel[float]`).++ Subclasses of `RootModel` get a plugin-generated `__init__` (see `get_metaclass_hook`), but `RootModel` itself (and type aliases of+ its parametrizations) use the explicitly typed `RootModel.__init__`, which should follow `init_typed` too.+ """+ if fullname == ROOT_MODEL_FULLNAME and not self.plugin_config.init_typed:+ return root_model_init_signature_callback+ return None+ def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: """Adjust return type of `from_orm` method call.""" if fullname.endswith('.from_orm'):@@ -284,6 +297,22 @@ class PydanticPluginConfig: return {key: getattr(self, key) for key in self.__slots__} +def root_model_init_signature_callback(ctx: FunctionSigContext) -> FunctionLike:+ """Type the `root` argument of a `RootModel` instantiation as `Any`, like fields in plugin-generated `__init__`s.++ Generic signatures (e.g. a bare `RootModel(...)` call) are left untouched, as the root type is inferred+ from the argument, and replacing it with `Any` would prevent this inference.+ """+ signature = ctx.default_signature+ if signature.is_generic():+ return signature+ arg_types = [+ AnyType(TypeOfAny.special_form) if arg_name == 'root' else arg_type+ for arg_name, arg_type in zip(signature.arg_names, signature.arg_types, strict=True)+ ]+ return signature.copy_modified(arg_types=arg_types)++ def from_attributes_callback(ctx: MethodContext) -> Type: """Raise an error if from_attributes is not enabled.""" model_type: Instancetests/mypy/modules/root_model_init.pynew file mode 100644index 00000000..e559dbb5@@ -0,0 +1,23 @@+from typing_extensions import assert_type++from pydantic import RootModel++FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+ pass+++# Values that can be validated to the root type are accepted unless `init_typed` is enabled:+alias_positional = FloatRootModel('1.0')+alias_keyword = FloatRootModel(root='1.0')+subclass_positional = FloatRootModelSubclass('1.0')++assert_type(alias_positional.root, float)+assert_type(alias_keyword.root, float)+assert_type(subclass_positional.root, float)++# The root type is still inferred when `RootModel` is not parametrized:+inferred = RootModel(1)+assert_type(inferred.root, int)tests/mypy/outputs/mypy-default_ini/root_model_init.pynew file mode 100644index 00000000..a3b644c1@@ -0,0 +1,26 @@+from typing_extensions import assert_type++from pydantic import RootModel++FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+ pass+++# Values that can be validated to the root type are accepted unless `init_typed` is enabled:+alias_positional = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+alias_keyword = FloatRootModel(root='1.0')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "float" [arg-type]+subclass_positional = FloatRootModelSubclass('1.0')+# MYPY: error: Argument 1 to "FloatRootModelSubclass" has incompatible type "str"; expected "float" [arg-type]++assert_type(alias_positional.root, float)+assert_type(alias_keyword.root, float)+assert_type(subclass_positional.root, float)++# The root type is still inferred when `RootModel` is not parametrized:+inferred = RootModel(1)+assert_type(inferred.root, int)tests/mypy/outputs/mypy-plugin-strict_ini/root_model_init.pynew file mode 100644index 00000000..a3b644c1@@ -0,0 +1,26 @@+from typing_extensions import assert_type++from pydantic import RootModel++FloatRootModel = RootModel[float]+++class FloatRootModelSubclass(RootModel[float]):+ pass+++# Values that can be validated to the root type are accepted unless `init_typed` is enabled:+alias_positional = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+alias_keyword = FloatRootModel(root='1.0')+# MYPY: error: Argument "root" to "RootModel" has incompatible type "str"; expected "float" [arg-type]+subclass_positional = FloatRootModelSubclass('1.0')+# MYPY: error: Argument 1 to "FloatRootModelSubclass" has incompatible type "str"; expected "float" [arg-type]++assert_type(alias_positional.root, float)+assert_type(alias_keyword.root, float)+assert_type(subclass_positional.root, float)++# The root type is still inferred when `RootModel` is not parametrized:+inferred = RootModel(1)+assert_type(inferred.root, int)tests/mypy/test_mypy.pyindex c66f1964..cb489691 100644@@ -107,6 +107,9 @@ 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_model_init.py'),+ ('mypy-plugin-strict.ini', 'root_model_init.py'),+ ('mypy-default.ini', 'root_model_init.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]