Backtestspydanticrun-20260923-170312#12978
mypy [arg-type]-error when passing in type that can be converted to RootModel
The merged fix was judged better than our patch.
No judgment was produced for this ticket. It counts as an error in the run total.
Solve
29m 1s25 turns
Wall-clock time in the container
Full test suite
1 new failure
5,716 passed · 1,065 skipped · 6,782 total
Contamination audit
Unknown
See the audit notes for this run
Patch size
34vs 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/root_model.pyindex d2900433..73665f17 100644@@ -57,7 +57,7 @@ class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetac ) super().__init_subclass__(**kwargs) - def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None: # type: ignore+ def __init__(self, /, root: Any = PydanticUndefined, **data) -> None: # type: ignore __tracebackhide__ = True if data: if root is not PydanticUndefined:tests/mypy/modules/root_models.pyindex 804d1d43..bb5ec328 100644@@ -46,3 +46,11 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[]) assert_type(m.m1, Maybe[int])+++# https://github.com/pydantic/pydantic/issues/12978+# A coercible value passed to a parametrized `RootModel` should be accepted at the+# type level, mirroring how `BaseModel` fields accept arbitrary input via `**data: Any`.+FloatRootModel = RootModel[float]+float_root = FloatRootModel('1.0')+assert_type(float_root, RootModel[float])tests/mypy/outputs/mypy-default_ini/root_models.pyindex 01cf5bbb..fd09c951 100644@@ -54,3 +54,11 @@ 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])+++# https://github.com/pydantic/pydantic/issues/12978+# A coercible value passed to a parametrized `RootModel` should be accepted at the+# type level, mirroring how `BaseModel` fields accept arbitrary input via `**data: Any`.+FloatRootModel = RootModel[float]+float_root = FloatRootModel('1.0')+assert_type(float_root, RootModel[float])tests/mypy/outputs/mypy-plugin_ini/root_models.pyindex 5bb30a04..2ab08fac 100644@@ -49,3 +49,11 @@ m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[]) assert_type(m.m1, Maybe[int])+++# https://github.com/pydantic/pydantic/issues/12978+# A coercible value passed to a parametrized `RootModel` should be accepted at the+# type level, mirroring how `BaseModel` fields accept arbitrary input via `**data: Any`.+FloatRootModel = RootModel[float]+float_root = FloatRootModel('1.0')+assert_type(float_root, RootModel[float])tests/mypy/outputs/pyproject-default_toml/root_models.pyindex 01cf5bbb..fd09c951 100644@@ -54,3 +54,11 @@ 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])+++# https://github.com/pydantic/pydantic/issues/12978+# A coercible value passed to a parametrized `RootModel` should be accepted at the+# type level, mirroring how `BaseModel` fields accept arbitrary input via `**data: Any`.+FloatRootModel = RootModel[float]+float_root = FloatRootModel('1.0')+assert_type(float_root, RootModel[float])
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
The review confirms the fix is correct and minimal. I already verified the full working tree contains only the 5 intended files. The work is complete.
Summary
What was wrongpydantic.RootModel[float]("1.0") raised a mypy [arg-type] error, while the analogous BaseModel field construction (Foo(f="1.0")) did not. The cause is in pydantic/root_model.py:60: the hand-written RootModel.__init__ typed its positional root parameter as the class TypeVar RootModelRootType, which binds to float for RootModel[float], rejecting a str. Because the pydantic mypy plugin does not regenerate __init__ for a parametrized generic alias, this strict source signature is what type checkers use — with or without the plugin. BaseModel.__init__, by contrast, is def __init__(self, /, **data: Any), so its field inputs are never rejected at the type level.
What I changed
pydantic/root_model.py:60— changed only therootparameter annotation fromRootModelRootTypetoAny, giving parity withBaseModel. The class-level fieldroot: RootModelRootType(governs the.rootattribute type) andmodel_construct's signature were left untouched.- Added a regression scenario to
tests/mypy/modules/root_models.py(FloatRootModel = RootModel[float]; float_root = FloatRootModel('1.0'); assert_type(float_root, RootModel[float])) and recorded the desired no-error post-fix state in the three fixtures (mypy-default_ini,pyproject-default_toml,mypy-plugin_ini).
Test evidence (mypy is not in the standard ./bt-test container, so I ran the mypy suite in the same Docker image with the repo's typechecking dependency group):
- Before fix: mypy emitted
Argument 1 to "RootModel" has incompatible type "str"; expected "float" [arg-type]on the new line under all three configs (error counts 9/9/4). - After fix: that error is gone with no new errors (counts 8/8/3). The actual
test_mypy.pycomparison against the fixtures passes: 3 passed for-k root_models, and the full mypy suite: 53 passed. - Runtime gate
./bt-test tests/test_root_model.py: 78 passed (change is type-only).
Requirements disposition
- "if the value can be converted … mypy should not raise an error" / parity between BaseModel-fields and RootModel-field: Implemented —
root: Anynow accepts coercible input; verified the reported[arg-type]error is eliminated across all three mypy configs and regression-tested. - Initial check "using Pydantic V2": informational only; no action needed.