Passing values dynamically into a python function chain call

Question:

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.

Asked By: George Udosen

||

Answers:

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.

Answered By: larsks
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.