I'm working on a Python project where I have two different Object-Document Mappers (ODMs), Beanie and Bunnet, for managing data in a database. Each ODM requires a different class structure for defining data models.
I have two separate classes for a User model, User_B1 for Bunnet and User_B2 for Beanie, both inheriting from their respective ODM's base document class.
Now, I'm building a Database class that dynamically selects the appropriate User class based on the user's choice of ODM at runtime. I'm currently using a dictionary (mapping) to map class names to their corresponding classes, and the call method to return the desired class instance based on its name.
class User_B1(UserModel, BunnetDocument):
class Settings:
name = "user"
class User_B2(UserModel, BeanieDocument):
class Settings:
name = "user"
class Database:
def __init__(self, odm_name: str):
if odm_name == "bunnet":
self.User = User_B1
elif odm_name == "beanie":
self.User = User_B2
else:
raise ValueError("Invalid ODM name")
def __call__(self, class_name: str) -> Any:
mapping = {"User": self.User}
return mapping[class_name]
if __name__ == "__main__":
db = Database("bunnet")
user = db.User
user = db("User")
obj_1 = user(
username="ali2",
password="Addsasad12365",
name="ali",
family="ali",
email="[email protected]",
)
obj_1.insert()
However, I'm looking for a cleaner and more dynamic way to implement the Database class without using a static mapping dictionary. Is there a way to dynamically return the appropriate class based on the provided class name, perhaps by inspecting the available classes within the Database instance or using some other Pythonic approach?
Additionally, I'd like to know if there's a better way to manage the User class selection, such that I don't need separate User_B1 and User_B2 classes, but instead, I can switch the parent class of the User dynamically based on the user's ODM choice. Is this feasible, or do I need to maintain separate classes for each ODM?
dynamically return the appropriate class based on the provided class name, you can use the built-in getattr() function to get the class object from the module namespace.
The management of the User class selection allows for the dynamic switching of the User's parent class based on the user's ODM choice. One approach is to establish a basic User class that contains the common properties and functions, and then define individual ODM subclasses that inherit from the base User class and the corresponding ODM's base document class. Here's how to change the User classes to utilize a base User class: