Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check a function's signature in Python?

Tags:

python

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.

like image 998
mjumbewu Avatar asked Aug 20 '10 20:08

mjumbewu


People also ask

What is the signature in Python?

A Signature object represents the call signature of a function and its return annotation. For each parameter accepted by the function it stores a Parameter object in its parameters collection. A Signature object has the following public attributes and methods: return_annotation : object.

WHAT IS function's signature?

A function signature (or type signature, or method signature) defines input and output of functions or methods. A signature can include: parameters and their types. a return value and type. exceptions that might be thrown or passed back.


1 Answers

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
like image 122
carl Avatar answered Sep 27 '22 17:09

carl