-
-
Notifications
You must be signed in to change notification settings - Fork 177
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
Multiple schemas for same nested type in data class with marshmallow-dataclass > 8.5.3 #762
Comments
Found the problem, but the reasoning is long, so first the solution 😁 In short: Solution:
And now the long story for those who are interested: The immediate reason for duplicating the output schemas is than whenever you call When apispec's So when the schema Exactly this is happening when you're doing This explains why repeated use of Most probably you're asking why it didn't fail without that function call 😁. Well, marshmallow-dataclass memoizes the class creation, meaning that if you try to invoke that So if you try to re-create the same class in the same context, then you're not actually re-creating it but get the same result, which is precisely what the OpenAPI plugin (and anyone else) expects. So the problem would happen every time you call Now that final missing piece: What are these circumstances? When hashes of the arguments of
The hash of the string and the base schema is straightforward: same values yield the same hash, different values usually yield different hashes. Calling frames, on the other hand, are implemented in CPython, their hash is their memory address, so whenever a new traceback is created, it'll yield a new hash, and whenever one is re-used, it'll yield the same 😞. But one function call has one traceback, so when at the end of your script you're executing
then the calling frame is that exact expression So the first sub-schema is created normally, then at the second the LRU cache kicks in, and returns the same sub-schema again. One nasty surprise: Try replacing that
What we can and need to do is avoid re-creating the schema classes, so NEVER call You may either call it once, like right after the dataclass declaration:
Or you may use the And that's how we got the example at the top 😁. |
When generating a schema for a single data class referencing same nested type in multiple fields each field get a separate schema. Even though it is the same type. Though, the trick is that this only happens if you first get the schema for the type in a different call context.
Code to reproduce the bug:
Running the above code will output the warning from marshmallow plugin:
UserWarning: Multiple schemas resolved to the name Foo. The name has been modified. Either manually add each of the schemas with a different name or provide a custom schema_name_resolver.
And the schema for Bar will look like:
The text was updated successfully, but these errors were encountered: