Is it possible to have arbitrary key names in pydantic?

Viewed 1725

I am trying to emulate a similar behavior to typescripts interface with arbitrary key names for a pydantic model, but am running in to some issues.

Consider the following in TS:

export interface SNSMessageAttributes {
    [name: string]: SNSMessageAttribute;
}

Is it possible to achieve this in pydantic?

Here is my python example code:

from pydantic import BaseModel, parse_obj_as
from typing import Optional

class Values(BaseModel):
    Value: str
    Type: str

class MessageAttributes(BaseModel):
    ArbitraryKey: Optional[Values]


class Mymodel(BaseModel):
    MessageAttributes: Optional[MessageAttributes]


data = {"MessageAttributes": {"ArbitraryKey": {"Type": "String", "Value": "TestString"}}}

parsed = parse_obj_as(Mymodel, data)

print(parsed.MessageAttributes.ArbitraryKey.Value)
# TestString

In this example, the property ArbitraryKey can be anything. But I cant possibly hardcode all the possible key names there could be. For instance, instead of ArbitraryKey, what if the key name was SomeTestKey?

I know I can use extra = 'allow in Config, but that wouldnt give the dot syntax that I can get when using parse_obj_as

My question is, if possible, can I do something similar to [name: string] in pydantic for property names?

1 Answers

After a discussion is Github, this is doing exactly what I was hoping for.

from pydantic import BaseModel, parse_obj_as
from typing import Dict, Optional

from pydantic import parse

class Values(BaseModel):
    Value: str
    Type: str


class Mymodel(BaseModel):
    MessageAttributes: Optional[Dict[str, Values]]


data = {"MessageAttributes": {"ArbitraryKey": {"Type": "String", "Value": "TestString"}}}

parsed = Mymodel.parse_obj(data)

print(parsed)
print(parsed.MessageAttributes['ArbitraryKey'].Type)
Related