Backtestspydanticrun-20261002-175417#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` with the metaclass hook so the plugin processes `RootModel` itself. They differ in how they loosen the `root` argument when `init_typed` is unset.
Patch B removes the guard for `RootModel` and lets `add_initializer` replace `RootModel`'s declared `__init__` with a plugin-generated one where `root` is `Any`. That fixes the reported `RootModel[float]('1.0')` case and the subclass case. However, it also removes the only place the class type variable appears in the constructor signature. A call on the unparametrized class, such as `RootModel(1)`, can then no longer infer the type parameter and likely resolves to `RootModel[Never]`. That is a regression in a common usage pattern. B neither handles nor tests it. Replacing the hand-written `__init__` wholesale (positional-only `root`, `**data`) with the generic generated one also carries some risk.
Patch A rewrites only the `root` argument of the existing `RootModel.__init__` to `Any`, which keeps the rest of the signature intact. It then adds a function-signature hook that restores the type variable when the call has unsolved type variables, so `RootModel(1)` still infers `RootModel[int]`. Its tests cover:
- the alias call, the keyword call and the subscripted call (`RootModel[float]('1.0')`), with `assert_type` checks;
- inference on the unparametrized class (`assert_type(RootModel(1), RootModel[int])`);
- subclasses;
- a new strict-ini case confirming that typed init still reports errors.
These tests directly guard the regression that B leaves open. A is more code, but it is well documented and consistent with the surrounding conventions. A is the more correct and better-tested 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
1h 12m
Wall-clock time in the container
Full test suite
No new failures
12,253 passed · 502 skipped · 12,755 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
223vs 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..12f02987 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,16 @@ 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` constructor calls."""+ 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'):@@ -536,6 +545,8 @@ class PydanticModelTransformer: is_settings = info.has_base(BASESETTINGS_FULLNAME) self.add_initializer(fields, config, is_settings, is_a_root_model)+ if info.fullname == ROOT_MODEL_FULLNAME:+ self.relax_root_model_initializer() self.add_model_construct_method(fields, config, is_settings, is_a_root_model) self.set_frozen(fields, self._api, frozen=config.frozen is True) @@ -966,6 +977,30 @@ class PydanticModelTransformer: add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType()) + def relax_root_model_initializer(self) -> None:+ """Annotates the `root` argument of the `RootModel.__init__` method as `Any`, if `init_typed` is not set.++ `RootModel` defines its own `__init__`, so `add_initializer()` does not generate one for it.+ Without this, calls like `RootModel[float]('1.0')` would be type checked against the `root` type,+ unlike the `__init__` generated for other models (including `RootModel` subclasses).++ See `root_model_init_signature_callback()` for how the type variable is still inferred+ when calling the unparametrized `RootModel` class.+ """+ if self.plugin_config.init_typed:+ return++ init_node = self._cls.info.names['__init__'].node+ if not isinstance(init_node, FuncDef) or not isinstance(init_node.type, CallableType):+ return # pragma: no cover++ init_type = init_node.type+ arg_types = [+ AnyType(TypeOfAny.special_form) if arg_name == 'root' else arg_type+ for arg_name, arg_type in zip(init_type.arg_names, init_type.arg_types, strict=True)+ ]+ init_node.type = init_type.copy_modified(arg_types=arg_types)+ def add_model_construct_method( self, fields: list[PydanticModelField],@@ -1276,6 +1311,28 @@ class ModelConfigData: setattr(self, key, value) +def root_model_init_signature_callback(ctx: FunctionSigContext) -> FunctionLike:+ """Restore the type variable as the type of the `root` argument when calling the unparametrized `RootModel` class.++ When `init_typed` is not set, the `root` argument of `RootModel.__init__` is annotated as `Any`+ (see `PydanticModelTransformer.relax_root_model_initializer()`). When the type variable is not+ yet solved (e.g. `RootModel(1)`), it would then be inferred as `Never`. In this case, the type variable is+ used again so that it can be inferred from the provided argument.+ """+ signature = ctx.default_signature+ ret_type = get_proper_type(signature.ret_type)+ if not signature.variables or not isinstance(ret_type, Instance) or ret_type.type.fullname != ROOT_MODEL_FULLNAME:+ return signature++ root_type = ret_type.args[0]+ return signature.copy_modified(+ arg_types=[+ root_type if arg_name == 'root' else arg_type+ for arg_name, arg_type in zip(signature.arg_names, signature.arg_types, strict=True)+ ]+ )++ def is_root_model(info: TypeInfo) -> bool: """Return whether the type info is a root model subclass (or the `RootModel` class itself).""" return info.has_base(ROOT_MODEL_FULLNAME)tests/mypy/modules/root_models.pyindex 804d1d43..5c80bbd4 100644@@ -46,3 +46,23 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[]) assert_type(m.m1, Maybe[int])++# Values that are validated (and converted) at runtime are accepted by the plugin's `__init__`, like for other models+# (only when `init_typed` is not set):+FloatRootModel = RootModel[float]++float_root_model = FloatRootModel('1.0')+assert_type(float_root_model, RootModel[float])+float_root_model_kw = FloatRootModel(root='1.0')+float_root_model_index = RootModel[float]('1.0')+assert_type(float_root_model_index, RootModel[float])++assert_type(RootModel(1), RootModel[int])+assert_type(RootModel('a'), RootModel[str])+++class IntRootModel(RootModel[int]):+ pass+++int_root_model = IntRootModel('1')tests/mypy/outputs/mypy-default_ini/root_models.pyindex 01cf5bbb..2802bc26 100644@@ -54,3 +54,27 @@ 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 are validated (and converted) at runtime are accepted by the plugin's `__init__`, like for other models+# (only when `init_typed` is not set):+FloatRootModel = RootModel[float]++float_root_model = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+assert_type(float_root_model, RootModel[float])+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_index = RootModel[float]('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+assert_type(float_root_model_index, RootModel[float])++assert_type(RootModel(1), RootModel[int])+assert_type(RootModel('a'), RootModel[str])+++class IntRootModel(RootModel[int]):+ pass+++int_root_model = IntRootModel('1')+# MYPY: error: Argument 1 to "IntRootModel" has incompatible type "str"; expected "int" [arg-type]tests/mypy/outputs/mypy-plugin-strict_ini/root_models.pynew file mode 100644index 00000000..9b00b17d@@ -0,0 +1,75 @@+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 are validated (and converted) at runtime are accepted by the plugin's `__init__`, like for other models+# (only when `init_typed` is not set):+FloatRootModel = RootModel[float]++float_root_model = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+assert_type(float_root_model, RootModel[float])+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_index = RootModel[float]('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+assert_type(float_root_model_index, RootModel[float])++assert_type(RootModel(1), RootModel[int])+assert_type(RootModel('a'), RootModel[str])+++class IntRootModel(RootModel[int]):+ pass+++int_root_model = IntRootModel('1')+# MYPY: error: Argument 1 to "IntRootModel" has incompatible type "str"; expected "int" [arg-type]tests/mypy/outputs/mypy-plugin_ini/root_models.pyindex 5bb30a04..88bac6b1 100644@@ -49,3 +49,23 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[]) assert_type(m.m1, Maybe[int])++# Values that are validated (and converted) at runtime are accepted by the plugin's `__init__`, like for other models+# (only when `init_typed` is not set):+FloatRootModel = RootModel[float]++float_root_model = FloatRootModel('1.0')+assert_type(float_root_model, RootModel[float])+float_root_model_kw = FloatRootModel(root='1.0')+float_root_model_index = RootModel[float]('1.0')+assert_type(float_root_model_index, RootModel[float])++assert_type(RootModel(1), RootModel[int])+assert_type(RootModel('a'), RootModel[str])+++class IntRootModel(RootModel[int]):+ pass+++int_root_model = IntRootModel('1')tests/mypy/outputs/pyproject-default_toml/root_models.pyindex 01cf5bbb..2802bc26 100644@@ -54,3 +54,27 @@ 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 are validated (and converted) at runtime are accepted by the plugin's `__init__`, like for other models+# (only when `init_typed` is not set):+FloatRootModel = RootModel[float]++float_root_model = FloatRootModel('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+assert_type(float_root_model, RootModel[float])+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_index = RootModel[float]('1.0')+# MYPY: error: Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]+assert_type(float_root_model_index, RootModel[float])++assert_type(RootModel(1), RootModel[int])+assert_type(RootModel('a'), RootModel[str])+++class IntRootModel(RootModel[int]):+ pass+++int_root_model = IntRootModel('1')+# MYPY: error: Argument 1 to "IntRootModel" has incompatible type "str"; expected "int" [arg-type]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'),
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]