Pydantic: model runtime type coercion more precisely
Describe the Bug
When using Pyrefly extension in vscode Pydantic models show Any type for fields. I would expect to see the same types as defined in the model.
Sandbox Link
No response
(Only applicable for extension issues) IDE Information
Pyrefly version: 0.40.1 Vscode version: 1.105.1 Python version: 3.14 Package manager: uv
Thanks for the report! This happens because, at runtime, Pydantic allows various types to be coerced to the specified field type (https://docs.pydantic.dev/latest/concepts/conversion_table/), which we've approximated with Any for now. One of our planned future improvements is to model type coercion more precisely.
For now, you can add strict=True (to the entire class or to a specific field), which will both disable runtime type coercion and make Pyrefly enforce types exactly.
Roger that. Is here the best place to track when that feature gets implemented? As soon as it is I'll probably be switching over to Pyrefly.
Yes, we'll update this issue when we implement this feature!
Roger that. Is here the best place to track when that feature gets implemented? As soon as it is I'll probably be switching over to Pyrefly.
out of curiosity, would you be looking for stricter typing behavior overall (so for example if you annotate a field in your model with an integer but try to pass a str, you would get a type error and red squiggles) or are you only looking at more informative type annotations on hover?
In other words, would you want to see the same behavior as when using strict=true, or something more lax than that?
Just more informative type annotations on hover, same as when strict = true.
Another idea, courtesy of @ndmitchell: in lax mode, we could preserve the strict mode field types but suppress the downstream type errors (perhaps using a different error code to make the suppression easier). Would require figuring out how to plumb enough information through to figure out what errors are due to pydantic lax vs. strict mode.
Another idea, courtesy of @ndmitchell: in lax mode, we could preserve the strict mode field types but suppress the downstream type errors (perhaps using a different error code to make the suppression easier). Would require figuring out how to plumb enough information through to figure out what errors are due to pydantic lax vs. strict mode.
I really like the idea of preserving strict mode field types. I would almost even be happy about automatic error suppression without any user intervention. I feel like if we do that, it defies all the theory... but in practice, not requiring the user to manually add suppressions would be nice.