Home > other >  Passing values dynamically into a python function chain call
Passing values dynamically into a python function chain call

Time:09-05

I have this python function:

def group_data(filter: str, filter_value: any, db_name: str, single=True, **kwargs) -> any:
   ....
   result = db.users.find({filter: filter_value}, kwargs)

   ...

Is it possible to pass the function argument db_name into the result variable function chain call to replace the users dynamically so I can use it for all the collections in my mongodb instance?

Example, say I have two collections users, and groups. I want to get the value of result like this:

 result = db.users.find(...), and 
 result = db.groups.find(...)

in the same group_data function by simple passing the arguments of users, and groups. A sort of chain function call interpolation.

CodePudding user response:

Are you looking for something like this?

def group_data(filter: str, filter_value: any, db_name: str, single=True, **kwargs) -> any:
    ...
    result = getattr(db, db_name).find({filter: filter_value}, kwargs)
    ...

You can use the getattr method to dynamically retrieve attributes from an object.

  • Related