Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Conditional class arguments

I have the following User class

class User(db.Model, CommonFields):
    __tablename__ = "user"
    __table_args__ = {"schema": "metadata"}

    email = db.Column(db.String)
    name = db.Column(db.String

    client = db.relationship("Clients", secondary=client_group)

I am inserting into the DB during the following function

def create_user(
    email: str,
    name: str,
    client_group: str
):

client_group = Client.get_client(client_group)

if client_group:
        user = User(
             email=email,
             name=name,
             client=[client_group]
        ) 
    else:
        user = User(
            email=email,
            name=name,
        )

    user = user.insert()
    return user_schema.dump(user)

Now this works, but it’s very repetitive.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question is there a way to do this to make it less repetitive?

A way to have conditional class arguments without repeating it in an if statement?

>Solution :

You can use a dictionary to pass named parameters dynamically. Then you can conditionally add an item to the dictionary.

user_dict = {"email": email, "name": name}
if client_group:
    user_dict["client"] = [client_group]
user = User(**user_dict)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading