Python Forum
Dynamically setting nested class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Dynamically setting nested class (/thread-36864.html)



Dynamically setting nested class - be_ams - Apr-06-2022

Hi,

I'm using pydantic to do some json validation. The incoming json will be in camel case but to keep my python as pythonic as possible (plus I don't like camel case) I want to be able to convert between snake case and camel case. Luckily pydantic supports doing this using nested classes. However, I'd like a way of doing this dynamically rather than having to add a nested class for every class and because my json structures are pretty heavily nested I end up with a load of classes.

I've put together a MRE below. In short I want to dynamically generated the nested Config class inside ClassA for `ClassB but by using a 'camelcase' decorator but it doesn't work.

from typing import ClassVar
from pydantic import BaseModel


def snake_to_camel(snake_str: str) -> str:
    """
    Convert a snake formatted string to a camel case formatted string
    """
    components = snake_str.split("_")
    return components[0] + "".join(x.title() for x in components[1:])


def camelcase(cls: ClassVar) -> ClassVar:
    """
    Decorator to dynamically generate the nested config class
    """
    cls.Config = type(cls.__name__ + '.Config', (object, ), {'alias_generator': snake_to_camel})
    return cls


class ClassA(BaseModel):
    some_var1: float
    some_var2: float

    class Config:
        alias_generator = snake_to_camel


@camelcase
class ClassB(BaseModel):
    some_var1: float
    some_var2: float


if __name__ == "__main__":
    class_input = {
        "someVar1": 65.0,
        "someVar2": 70.4
    }
    class_a = ClassA(**class_input)
    class_b = ClassB(**class_input)
This one has stumped me so any help would be greatly appreciated! Thanks!