Search code examples
pythonapplypeewee

How to programmatically call a class member function in Python?


how to programmatically call a class member function in Python?

For instance I've got a class Model in peewee, with various method attributes such as .select(), .join(), .where() etc...

Here's an example from the documentation.

query = (User
         .select(User.username, fn.COUNT(Favorite.id).alias('count'))
         .join(Tweet, JOIN.LEFT_OUTER)  # Joins user -> tweet.
         .join(Favorite, JOIN.LEFT_OUTER)  # Joins tweet -> favorite.
         .group_by(User.username))

To join multiple table, I've to call several times the join method. The problem is that I'd like to be able to call it n where n is an array of link, as my Models are programmatically defined, same for the links.

So it could be something like this:

query = (ModelA
         .select(*AllModels)
         .join(ModelB, JOIN.LEFT_OUTER, on=cond1)
         .join(ModelC, JOIN.LEFT_OUTER, on=cond2)
         .join(ModelD, JOIN.LEFT_OUTER, on=cond3)
         .join(ModelE, JOIN.LEFT_OUTER, on=cond4)

How can I apply programmatically the join calls using a loop or equivalent?

To generate the list of joins, I've a structure such as below

schema = {
        "datasets": {
        "a74d411f-412b-42b3-aa31-a1f687e0257e": {
            "oid": "5e585118de2ecd919a50fd94",
            "fullpath": "/vob/CABC/CABC123/ad/a/ae.sas7bdat"
        },
        "067a21c5-e512-49d7-bd2c-40fbb56e6f30": {
            "oid": "5e585118de2ecd919a50fd94",
            "fullpath": "/vob/CABC/CABC123/ad/a/dm.sas7bdat"
        },
        "067a21c5-e512-49d7-bd2c-40fbb56e6f31": {
            "oid": "5e585118de2ecd919a50fd94",
            "fullpath": "/vob/CABC/CABC123/ad/a/zn.sas7bdat"
        }
        },   
        "links": [
            {
                "dataset_origin": "a74d411f-412b-42b3-aa31-a1f687e0257e",
                "column_origin": "SUBJID",
                "dataset_target":  "067a21c5-e512-49d7-bd2c-40fbb56e6f30",
                "column_target": "SUBJID",
                "join_type": "INNER"
            },
            {
                "dataset_origin": "a74d411f-412b-42b3-aa31-a1f687e0257e",
                "column_origin": "SUBJID",
                "dataset_target":  "067a21c5-e512-49d7-bd2c-40fbb56e6f31",
                "column_target": "SUBJID",
                "join_type": "INNER"
            }
        ]
    }

Solution

  • Here you can just do a fold using a regular loop e.g.

    query = ModelA.select(*AllModels)
    for Model, cond in ...:
        query = query.join(Model, JOIN.LEFT_OUTER, on=cond)
    

    That aside, methods are accessed like any other attribute, so you can getattr(obj, method_name)(method_params...)