Rodrigo Farias Rezino
Rodrigo Farias Rezino

Reputation: 2799

How to check the number of arguments and method from a class has in runtime

Given the class

   class TestClassRequiredMethods:
        called = False

        def publish_db_flaws(self, x):
            self.called = True

I'd like to check if the class has a certain method and an expected amount of params. I solved half of it, now I can check if the object has the attribute but I can't find a way to check how many params are expected in this method.

if not hasattr(publisher, 'publish_db_flaws'):
    raise TypeError('The publisher must contain a "publish_db_flaws()" method')

Answer

The accepted answer is working fine for Python 2, if you are working with version 3, you may use:

import inspect 

class Publisher:
    def publish_db_flaws(self, params_string:str, params_integer:int):
        pass


publisher = Publisher()
print(inspect.signature(publisher.publish_db_flaws))
print(inspect.getfullargspec(publisher.publish_db_flaws))

Upvotes: 2

Views: 719

Answers (1)

mkiever
mkiever

Reputation: 891

In addition to hasattr you can use callable(publisher.publish_db_flaws) to check if the attribute is really a callable function.

More detail is available using inspect module as hinted in the comment by ForceBru. inspect.getfullargspec(publisher.publish_db_flaws) gives you information about argument names, if the function uses varargs or keyword args and any defaults. Similar information is available via inspect.signature. This gives you a Signature object which has a __eq__ method for easy comparison. Note, that this is the preferred method for Python3. getfullargspec is to be used if you need compatibility with the Python2 interface.

Upvotes: 1

Related Questions