1

I'm using FastAPI with Pydantic and I'm trying to achieve that my API accepts cammel case parameters, for this, I'm using the following

from pydantic import BaseModel
from humps import camelize
class CamelModel(BaseModel):
 class Config:
 alias_generator = camelize
 allow_population_by_field_name = True
class MyClass(CamelModel):
 my_field1: int
 my_field2: int
 my_field3: int

So far it works great, but MyClass is a base class for others classes, for example as

class MyNewClass(MyClass):
 my_field4: float

How can I get the MyNewClass to also use the camel case base class? I've tried something like

from typing import Union 
class MyNewClass(Union[MyClass, CamelModel]):
 my_field4: float

But I'm getting this error

TypeError: Cannot subclass <class 'typing._SpecialForm'>

Is there any way to accomplish this? Thanks!

InSync
12.2k5 gold badges22 silver badges60 bronze badges
asked Sep 21, 2020 at 19:31

1 Answer 1

2

What you are trying to achieve is called multiple inheritance. Since you are inheriting from a class which inherited from the CamelModel, there's no need to inherit it again

The appropriate code should be

class MyNewClass(MyClass):

It's the python syntax for multiple inheritance. See an extensive example here https://www.python-course.eu/python3_multiple_inheritance_example.php#An-Example-of-Multiple-Inheritance

The code you are using (class MyNewClass(Union[MyClass, CamelModel]):) is used for declaring data types, which is kinda of correct, but not in the right place. Typing is almost only (as far as I've seen) used for parameters of functions.

NOTE I did not test the piece of code above, but I'm pretty sure it works. Let me know if there are any problems

answered Sep 21, 2020 at 21:06
Sign up to request clarification or add additional context in comments.

2 Comments

You are right, this is just class inheritance, this way should work just fine, thanks for the response!
You're welcome. If it worked, please mark the answer as accepted, so that it will not appear as open.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.