New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Instances share objects after copy or created from unpacking a dict #249
Comments
Hi, thanks for reporting. I agree entirely that
async def my_view(request):
try:
m = Model(**await request.json())
except ValidationError as e:
raise BadRequestError(**e.dict())
... do stuff with m This is the primary use case for pydantic (at least for me) and I want it to remain as performant as possible (both in terms of CPU and memory). I really don't want to copy all the data from the result of We also can't add keyword arguments to For the same kinds of reason I don't really want Does that make sense? Would you be willing to submit a PR for some or all of this? |
BTW, you can reference other issues with |
Totally agree that preformance is key. If a true copy is needed at initialization the user can do that without the need for a seperate method. And a user can always do a deepcopy after converting dict(). So let's just focus on the initial problem I had, the copy() method (I noticed the other behaviours while testing). Do you want to change the way copy() works or should we add a deepcopy() method to seperate the two? |
I think we add a I doubt many people actually use |
We use it during unit test where we want to have a base data model to start with and then just change what's needed for the test. That's how I ran into this issue, made a copy of the data, first test emptied a list in a dict and then the next test had nothing to check for despite copying the base data. So I do think there is good use for it. I'll look into doing a PR for this. Don't know then I can finish it though, but will try to have something for review in a week or so. |
Great, thanks so much. I agree it's useful. |
Took a little longer than expected before I had time to do this, but now it's done. |
This is related to #154 and I'm using pydantic v0.12.1
Here is a simple example to show what I mean.
Another example when created by unpacking a dictionary.
BaseModel.dict() seems to create copies correctly and can be used instead of .copy() to create a new object as seen with model3 in this example.
I think this is quite serious since you can't know if you are working with a true copy of a model or not.
I see two things that need to be fixed.
.copy() should create a deepcopy that doesn't share any objects with the model it was copied from. User created classes have to support deepcopy operations to work correctly.
BaseModel(**dict) need to make sure that all items in the dict are deepcopied from the unpacked dictionary.
The text was updated successfully, but these errors were encountered: