Skip to content
Advertisement

Is there a clean way to build a line of code with methods call from a dictionary in Python?

I would like to build a SQLAlchemy command to get information from a database table. To do it I use this lines of code :

def new_rows(table, target):

    command = select(table)

    return command_execution(command)

Target is a dictionary and I would like that if a key is present in target, I add it after my select command. For example, if target is :

target = {
    "limit": 20,
    "order_by": "name"
}

then my command would become :

command = select(table).limit(20).order_by(table.c["name"])

Is there a way to do this in a clean way in Python ?

Advertisement

Answer

The cleanest route is probably something like:

   command = select(table)
   if (value := target.get('limit')):
       command = command.limit(value)
   if (value := target.get('order_by')):
       command = command.order_by(value)
   ...

If you’re absolutely positive that everything in the table is a method that can be applied to a command and that they’re in the right order, you could write:

    command = select(table)
    for key, value in target.items():
        command = getattr(command, key)(value)

but it’s really ugly, and you should only do it if you can’t enumerate your possible suffixes.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement