How to index a pydantic model using a string object, returning a pydantic model? #3463
Unanswered
thomasaarholt
asked this question in
Question
Replies: 1 comment
-
|
Right, I've just learnt about class IndexableBaseModel(BaseModel):
"""Allows a BaseModel to return its fields by string variable indexing"""
def __getitem__(self, item):
return getattr(self, item)Now if I replace all references to BaseModel in the previous example with Is there a rationale for why this isn't default behaviour with pydantic? Would a user expect it to function as a dict? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! Thanks for creating a really cool library! It's keeping us sane when reading in config files.
On that topic, we've written the following config file, read in as a dict:
The idea is that we have a list of
learnerswith several different parameters, and if we run the program without specifying anything, it chooses thedefault_learnermodel name.The above dict is parsed into the following pydantic BaseClass:
I would like to access the
paramfield from model1 usingconfig.default_learnerwithconfig.learners. That is, something likeconfig.learners[config.default_learner].params. But BaseModel is not subscriptable. I've tried e.g.config.learners.dict()[config.default_learner], but that returns a dict, and I would like to keep using the nice pydantic propertya.bchaining.I could do
MLModel(**config.learners.dict()[config.default_learner]).param, or evenbut this seems rather non-ideal 🤪
Are there any better suggestions or solutions?
Beta Was this translation helpful? Give feedback.
All reactions