Bharti Rawat
Bharti Rawat

Reputation: 2073

How can I get keyword/positional arguments of any method in Python

As I am developer of Python and works at different different technologies.

So sometimes I really feel that there should be a method which can tell both the KEYWORD ARGUMENT and POSITIONAL ARGUMENTSof any method.

Example:

response(url="http://localhost:8080/core",data={"a":"12"},status=500)

Response have many keyword/positional arguments like url,data, status.

There can be many more keyword arguments of response method which I do not mentioned in above example. So I want to know all total number of keyword argument of a method.

So if anyone knows any method in Python which can tell about keyword argument please share it.

Upvotes: 0

Views: 232

Answers (1)

Michael Kazarian
Michael Kazarian

Reputation: 4462

Try inspect module:

In [1]: def a(x, y , z): pass
In [2]: import inspect
In [3]: inspect.getargspec(a)
Out[3]: ArgSpec(args=['x', 'y', 'z'], varargs=None, keywords=None, defaults=None)

or use decorator:

def a(f):
    def new_f(*args, **kwds):
        print "I know my arguments. It:"
        print "args", args
        print "kwds", kwds
        print "and can handle it here"
        return f(*args, **kwds)
    return new_f
@a
def b(*args, **kwargs):
    pass

b(x=1, y=2)

Upvotes: 1

Related Questions