Python Forum
Dynamically setting nested class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamically setting nested class
#1
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  dynamically define class's michavardy 1 2,094 Feb-26-2019, 04:20 PM
Last Post: buran
  Help creating a class instance dynamically Kotevski 9 5,386 Aug-17-2018, 05:23 AM
Last Post: Gribouillis
  setting parameters for functions and nested functions mepyyeti 5 3,878 Feb-25-2018, 06:42 PM
Last Post: snippsat
  setting base class attribute bb8 1 2,535 Feb-13-2018, 06:37 PM
Last Post: nilamo
  Import class dynamically voltron 4 4,785 Feb-05-2018, 01:24 PM
Last Post: voltron

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020