Checking Signature of Function Parameter

Chris Rebert clp2 at rebertia.com
Mon Aug 29 03:21:57 CEST 2011


On Sun, Aug 28, 2011 at 2:20 PM, Travis Parks <jehugaleahsa at gmail.com> wrote:
> I am trying to write an algorithms library in Python. Most of the
> functions will accept functions as parameters. For instance, there is
> a function called any:
>
> def any(source, predicate):
>    for item in source:
>        if predicate(item):
>            return true;
>    return false;
>
> There are some things I want to make sure of. 1) I want to make sure
> that source is iterable. 2) More importantly, I want to make sure that
> predicate is callable, accepting a thing, returning a bool.
<snip>
> I am more concerned with the number of parameters.

That can be introspected using the `inspect` module:
http://docs.python.org/library/inspect.html#inspect.getargspec

> Finally, can I use decorators to automatically perform these checks,
> instead of hogging the top of all my methods?

Certainly. Although, as others have said, the cost-benefit ratio of
adding code to perform such somewhat-redundant checks might make it
not worth the trouble.

Cheers,
Chris



More information about the Python-list mailing list