tags:

views:

91

answers:

3

I'm looking for a way to check the number of arguments that a given function takes in Python. The purpose is to achieve a more robust method of patching my classes for tests. So, I want to do something like this:

class MyClass (object):
    def my_function(self, arg1, arg2):
        result = ... # Something complicated
        return result

def patch(object, func_name, replacement_func):
    import new

    orig_func = getattr(object, func_name)
    replacement_func = new.instancemethod(replacement_func, 
                           object, object.__class__)

    # ...
    # Verify that orig_func and replacement_func have the 
    # same signature.  If not, raise an error.
    # ...

    setattr(object, func_name, replacement_func)

my_patched_object = MyClass()
patch(my_patched_object, "my_function", lambda self, arg1: "dummy result")
# The above line should raise an error!

Thanks.

+3  A: 

You should use inspect.getargspec.

hwiechers
A: 

The inspect module allows you to examine a function's arguments. This has been asked a few times on Stack Overflow; try searching for some of those answers. For example:

http://stackoverflow.com/questions/218616/getting-method-parameter-names-in-python

Richard Fearn
I see. I did a bit of searching before posting, but I guess I should have use more search terms. Sorry for the bother.
mjumbewu
No problem. Better to point to you to the other answers, though, than just repeat everything here.
Richard Fearn
A: 

You can use:

import inspect
len(inspect.getargspec(foo_func)[0])

This won't acknowledge variable-length parameters, like:

def foo(a, b, *args, **kwargs):
    pass
carl