At work, I needed to list all the method arguments that belong to a Python module, so I looked it up. I think it's a very niche task, but instead of a memo (^ _ ^;)
Explore from top-level class and module meta information with the inspect module.
Details of the inspect module-> https://docs.python.org/2/library/inspect.html
inspect.getmembers(object)
All members belonging to the object given as an argument are returned in a list of the form tuple ('name','value').
inspect.getargspec(func)
The argument information of the function given to the argument is returned in the format of tuple (args, varargs, keywords, defaults). args contains a list of arguments.
Below is an example.
An example is Trove's python client, which is openstack's DBaaS. (I wanted to check all the arguments of the I / F that issues the API to trove.)
troveclient.v1.client.Client Structure that has instances of various classes in the instance variable of the class of Below is the code to check the method arguments that each instance has
import inspect
import troveclient.v1.client as dbcli
cli = dbcli.Client('', '', '')
cli_info = inspect.getmembers(cli)
for rds_info in cli_info:
if rds_info[0][0] != "_":
# Above if statement is for removing private class
for info in inspect.getmembers(rds_info[1]):
if inspect.ismethod(info[1]):
if info[0][0] != "_":
# Above "if" statement is for removing private method
for arg in inspect.getargspec(info[1]).args:
print rds_info[0], info[0], arg
Below is the code to investigate the CLI I / F getmembers really fetches all the attributes I also got the attributes declared in the decorator.
import inspect
import troveclient.v1.shell as rdscli
for i in inspect.getmembers(rdscli):
if inspect.isfunction(i[1]):
for j in inspect.getmembers(i[1]):
if j[0] == 'arguments':
# Above if statement is for retrieving decorators attribute.
for k in j[1]:
required = 'y'
default = 'None'
helpstr = k[1].get('help')
if 'default' in k[1].keys():
required = 'n'
default = k[1].get('default')
if default is None:
default = 'None'
if helpstr is None:
helpstr = 'None'
if isinstance(default, list):
default = "[" + ",".join(default) + "]"
print(i[0] + "|" + k[0][0] + "|" + required +
"|" + default + "|" + helpstr)
Recommended Posts