pydantic / pydantic-core

Core validation logic for pydantic written in rust
MIT License
1.38k stars 233 forks source link

Type stubs: Incorrect return type on validate_assignment #947

Open hassec opened 1 year ago

hassec commented 1 year ago

Is it possible that the below type stub is incorrect?

https://github.com/pydantic/pydantic-core/blob/6a139753af85fc7bb6b34f26c1328994506f94ee/python/pydantic_core/_pydantic_core.pyi#L174-L183

In the below example the returned value seems to be a of type A.

from pydantic import BaseModel

class A(BaseModel, validate_assignment=True):
    i: int

a = A(i=1)
x = a.__pydantic_validator__.validate_assignment(a, "i", 3)
print(type(x))  # <class '__main__.A'>
print(x is a)  # True
davidhewitt commented 1 year ago

Yes, the type stub looks pretty wonky. In general this should return the model / dataclass / TypedDict instance which has been validated. There is some complexity on the Rust side which is probably what led to this stub. @adriangb maybe you have an idea how we might be able to improve this?

davidhewitt commented 1 year ago

Maybe it's better to just make the type stub here -> Any?

sydney-runkle commented 4 weeks ago

@Viicos, maybe a good issue for you, as our resident typing guru.

Viicos commented 3 weeks ago

If the return type changes depending on the provided core schema, SchemaValidator should ideally be made generic. But if not possible, then Any is probably the way to go. But I'm not sure in which scenarios the current return type is valid?

sydney-runkle commented 2 weeks ago

If the return type changes depending on the provided core schema, SchemaValidator should ideally be made generic. But if not possible, then Any is probably the way to go.

Agreed re generic, and agreed re Any for now.