Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361342

Given a method name as string, how to get the method instance?

I've a class Client which has many methods:

class Client:
    def compute(self, arg):
          #code
    #more methods

All the methods of this class runs synchronously. I want to run them asynchronously. There are too many ways to accomplish this. But I'm thinking along these lines:

AsyncClient = make_async(Client) #make all methods of Client async, etc!

client = AsyncClient()           #create an instance of AsyncClient

client.async_compute(arg)        #compute asynchronously
client.compute(arg)              #synchronous method should still exist!

Alright, that looks too ambitious, and I feel it can be done.

So far I've written this:

def make_async(cls):

     class async_cls(cls):  #derive from the given class

         def __getattr__(self, attr):
               for i in dir(cls):
                   if ("async_" + i) == attr:
                         #THE PROBLEM IS HERE
                         #how to get the method with name <i>?
                         return cls.__getattr__(i) # DOES NOT WORK

     return async_cls

As you see the comment in the code above, the problem is to get the method given its name as string. How to do that? Once I get the method, I would wrap it in async_caller method, etc — the rest of the work I hope I can do myself.

Upvotes: 1

Views: 106

Answers (1)

Tarzan
Tarzan

Reputation: 529

The function __getattr__ just works with class instance, not class. Use getattr(cls, method_name) instead, it will solve the problem.

getattr(cls, method_name)

Upvotes: 4

Related Questions