-
-
Notifications
You must be signed in to change notification settings - Fork 113
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
KeyError when using configure_tagged_union with existing field #483
Comments
There's a way but it's somewhat complex so let me ask you a few questions first. The If that is true, maybe this is redundant information and instead of checking for A second easy approach you can take is turn your class into: from typing import Literal
@attrs.define
class SpecialDevice:
hostname: str
port: int
type: Literal["special"] = "special" Then cattrs will still remove the field from the payload, but there is a default on the class level so the value will still be set. You can take this one step further an make it a class variable instead of an instance variable: from typing import ClassVar, Literal
@attrs.define
class SpecialDevice:
hostname: str
port: int
type: ClassVar[Literal["special"]] = "special" These change the data modeling strategy somewhat so let me know if they work for you, if not we can consider different solutions. |
Thank you for your response. You're correct that the If this is not possible to keep the value of the "type" field when using the key for |
Ok, so the problem is that the First, we change the tag name to configure_tagged_union(
Device, c, tag_name="_type", tag_generator=tag_generator, default=StandardDevice
) That way, the strategy will pop out Now, we need to actually copy First, we'll fetch the function the strategy generated for us. Then, we just wrap this function in our own function, and register that on the converter. base_hook = c._union_struct_registry[Device]
def our_hook(value, _):
value["_type"] = value["type"]
return base_hook(value, _)
c.register_structure_hook(Device, our_hook) And now structuring should work. I think I'll rework how some of this works internally so this process will be cleaner in the next version of cattrs (you won't have to use an internal registry). |
Description
I am trying to create a union type which uses an existing key to determine the type to use.
Looking at an example object, the "type" key word is used by the application to set up the correct type of device, and I want to use it to enable additional configuration settings:
When I use
configure_tagged_union(..., tag_name="type" ...)
, the "type" key seems to be consumed and is no longer available for the Device data class. This is causing a key error during the structure process.What do I need to do to keep the "type" data available and use it for the tagged union?
What I Did
Example code:
Traceback:
The text was updated successfully, but these errors were encountered: