How to get the formal args of a function object?

Jeff McNeil jeff at jmcneil.net
Thu May 14 16:33:55 EDT 2009


You can pull it out of f.func_code.co_varnames, but I don't believe
that's a very good approach. I tend to veer away from code objects
myself.

If you know how many arguments are passed into the wrapped function
when it's defined, you can write a function that returns your
decorator. As an example...

def validate_params(c):
    def the_decorator(f):
        def wrapper(*args):
            if len(args) != c:
                raise Exception("Bad things, Man.")
            return f(*args)
        return wrapper
    return the_decorator

@validate_params(2)
def add(a,b):
    return a+b

add(1,2)
add(1,2,3)

$ ./test.py
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    add(1,2,3)
  File "test.py", line 5, in wrapper
    raise Exception("Bad things, Man.")
Exception: Bad things, Man.

Jeff



On May 14, 3:31 pm, kj <so... at 987jk.com.invalid> wrote:
> Suppose that f is an object whose type is 'function'.
>
> Is there a way to find out f's list of formal arguments?
>
> The reason for this is that I'm trying to write a decorator and
> I'd like the wrapper to be able to check the number of arguments
> passed.  Specifically, I'd like the wrapper to look as shown below:
>
> def _wrap(f):
>     def wrapper(self, *params):
>         n_expected = len(f.FORMAL_ARGS)
>         n_received = len(params)
>         if n_received is not n_expected:
>             raise RuntimeError("Wrong number of arguments passed "
>                                "to %s" % f.__name__)
>         return self.send_jsonrpc_request(f.__name__, params)
>     return wrapper
>
> ...but I'm missing something like the hypothetical attribute
> FORMAL_ARGS above.
>
> TIA!
>
> Kynn
>
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.




More information about the Python-list mailing list